【问题标题】:Trailing tab in the string not getting printed using the print function in python (python3)Trailing tab in the string not getting printed using the print function in python (python3)
【发布时间】:2022-12-02 11:50:30
【问题描述】:

I am trying to print a string with \t at both beginning and end, like below.

name2print="\tabhinav\t"
lastname="gupta"
print(name2print,lastname)
Expected output should be 
        abhinav         gupta

But the actual output is
        abhinav  gupta

I tried with lstrip like this and as expected strips only the beginning "\t" and prints the trailing "\t"

print(name2print.lstrip(),lastname)

Output: 
abhinav         gupta

If lstrip() can print the trailing "\t" then why is the print statement ignoring the trailing tab character in the first string while printing? I think I am missing something basic. Please help.

【问题讨论】:

    标签: python string printing tabs


    【解决方案1】:

    The output is correct. adds a variable number of spaces so that the next printed character is at a position which is a multiple of 8.

    In your example the first adds 8 spaces, then you print abhinav (7 characters), the next tab adds 1 space to make it a multiple of 8, then the , in your print statements adds 1 space, then you print gupta:

            abhinav  gupta
    123456781234567812345678
    

    If you always want to print 8 spaces, use " ".

    【讨论】:

      【解决方案2】:

      When you print a tab character, Python uses it to align the string to the end of a 4 character boundary so that the next thing that gets printed is aligned to the next boundary. So you will not always get 4 spaces. Rather, you'll get between 1 and 4 spaces. Here's some code to demonstrate this:

      print('	a	','bbbb')
      print('	aa	','bbbb')
      print('	aaa	','bbbb')
      print('	aaaa	','bbbb')
      print('	aaaaa	','bbbb')
      print('1234567890123456')
      

      Result:

          a    bbbb
          aa   bbbb
          aaa  bbbb
          aaaa     bbbb
          aaaaa    bbbb
      1234567890123456
      

      【讨论】:

        猜你喜欢
        • 2020-11-11
        • 1970-01-01
        • 1970-01-01
        • 2017-07-09
        • 2022-12-02
        • 2023-02-24
        • 2013-09-30
        • 2022-12-02
        • 2022-11-20
        相关资源
        最近更新 更多