在python中对齐列
我只想读这个文本文件的第四列和第五列 sample.txt在python中对齐列,python,format,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
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
我可以这样做,但输出的格式不是我想要的
输出
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
所需输出
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
这是我的代码(我使用了一些格式,但仍然没有提供所需的输出):
这一行:
itemsales=item+"{0:>33}".format(strsales)
正在将数字填充到33个位置。但是项的长度是可变的,这会导致对齐失效。仔细看,你会发现第1行和第2行的不均匀度是2个位置,这正是男装
和女装
之间的长度差异。您需要将这两个变量填充到固定数量的位置。试试这个
itemsales = "{0:<33}{1:>18}".format(item,strsales)
itemsales=“{0:18}”。格式(item,strsales)
@BoarGules如何将对齐的数字动态作为变量?如:itemsales=“{item:{dynamicwidth}}”。格式(item=item,strsales=strsales,dynamicwidth=18)
。详情请参阅。但你不应该在这样的评论中提出补充问题。一般来说,只有原始答案的作者才能阅读。如果那个人已经离开了,你就不会得到回应。