在python中对齐列

时间:2018-01-21 09:50:02

标签: python format

我只想阅读此文本文件的第四和第五列

sample.txt的

2012-01-01  09:00   San Jose    Men's Clothing  214.05  Amex
2012-01-01  09:00   Fort Worth  Women's Clothing    153.57  Visa
2012-01-01  09:00   San Diego   Music   66.08   Cash

我能够做到这一点,但输出的格式不是我想要的。

输出

Men's Clothing                           214.05
Women's Clothing                           153.57
Music                            66.08

所需的输出

Men's Clothing                             214.05
Women's Clothing                           153.57
Music                                       66.08

这是我的代码(我使用了一些格式但它还没有给我所需的输出):

for line in open("sample.txt"):

      strsales=line.split()[-2]
      item=line.split('\t')[3]
      itemsales=item+"{0:>33}".format(strsales)
      print(itemsales)

1 个答案:

答案 0 :(得分:2)

这一行:

itemsales=item+"{0:>33}".format(strsales)

数字填充到33个位置。但是item的长度是可变的,这会导致你的对齐结束。仔细观察,你会发现第1行和第2行的不均匀性是2个位置,这正是Men's ClothingWomen's Clothing之间的长度差异。您需要将两个变量填充到常数个位置。试试这个

itemsales = "{0:<33}{1:>18}".format(item,strsales)