Tabs in print are not consistent python

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

    Compute the maximum width needed for each column and then use string formatting to compose a format which specifies the desired width:

    data = [['first:ThisIsLong', 'second:Short'],
            ['first:Short', 'second:ThisIsLong'],
            ['first:ThisIsEvenLonger', 'second:Short']]
    
    widths = [max([len(item) for item in col]) for col in zip(*data)]
    fmt = ''.join(['{{:{}}}'.format(width+4) for width in widths])
    for row in data:
        print(fmt.format(*row))
    

    yields

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

提交回复
热议问题