Tabs in print are not consistent python

后端 未结 5 1141
庸人自扰
庸人自扰 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:40

    The most Pythonic way to do this is:

    string_one = 'first:ThisIsLong'
    string_two = 'second:Short'
    
    print(f'{string_one:<20s} {string_two:<10s}')
    

    You can use an F-string (format string) to align the strings instead. For example, you can tell python that the first column should be 20 characters long, and the second should be 10, left aligned.

    using this F-string will print:

    first:ThisIsLong     second:Short
    

    Broken Down

    f'{insert_variable_here:<20s}' says:

    : take all before this and format as: < left align, 20 at least 20 characters, s because it's a string.

    Credit to mjwunderlich for the format.

提交回复
热议问题