Tabs in print are not consistent python

后端 未结 5 1147
庸人自扰
庸人自扰 2021-01-11 12:54

I want to have real tabs in a print but \\t only puts spaces. Eg:

 first:ThisIsLong         second:Short
 first:Short         second:ThisIsLong
         


        
5条回答
  •  伪装坚强ぢ
    2021-01-11 13:33

    The Python print function sends strings to standard output. What standard output does with those strings depends on the output device. The default interpretation of \t is to advance to the next tab stop, which by convention is the character position which is the next multiple of 8 after the position in which \t occurs (counting character positions from the left beginning with 0).

    For example, if I run:

    babynames = [('kangaroo', 'joey'), ('fox', 'kit'), ('goose','gosling')]
    for x,y in babynames: print(x + '\t' + y)
    

    I get:

    kangaroo        joey
    fox     kit
    goose   gosling
    

    I got the above in IDLE. kangaroo occupies columns 0-7. \t is in column 8, hence the next multiple of 8 (the next tab stop) after the tab is in column 16 -- which is indeed where you see joey. In the next two lines -- the next tab stop after the first word is in column 8. This shows that (at least in the IDLE shell) Python is using real tabs.

    Tabs in this sense are somewhat annoying. They can only be used to align variable-length string data with a certain amount of annoying difficulty. As others have indicated the solution is to not use tabs but instead use format

提交回复
热议问题