-------- Final Receipt --------
Milk, 2 Litres $ 2
Potatoes $ 7.5
Sugar $ 3.5
我希望这个print语句是
-------- Final Receipt --------
Milk, 2 Litres $ 2
Potatoes $ 7.5
Sugar $ 3.5
这是我的印刷版
for mydata in zip(*list(product_in_basket.values())[:-1]):
print(mydata[1],'$',mydata[2])
和product_in_list是嵌套字典
代码完全正常但需要我的输出样式
答案 0 :(得分:0)
您可以使用ljust
:
data = [['-------- Final Receipt --------'], ['Milk, 2 Litres', '$ 2'], ['Potatoes', '$ 7.5'], ['Sugar', '$ 3.5']]
v, _ = max(data[1:], key=lambda x:len(x[0]))
final_data = data[0][0]+'\n'+'\n'.join(a.ljust(len(v)+3)+b for a, b in data[1:])
输出:
-------- Final Receipt --------
Milk, 2 Litres $ 2
Potatoes $ 7.5
Sugar $ 3.5
答案 1 :(得分:0)
您可能希望使用ljust
用空格填充字符串。这样每列都有一定的宽度。
header = " -------- Final Receipt --------"
l = [["Milk, 2 Litres", 2], ["Potatoes", 7.5], ["Sugar", 3.5]]
print(header)
for mydata in l:
price = "$ {0}".format(mydata[1])
print("{0}{1}".format(mydata[0].ljust(16),price.ljust(16)))
我做了len(header)
以确定您的标题是32个字符,所以现在每列占用了一半(16)。
请参阅:How can I fill out a Python string with spaces?
结果:
-------- Final Receipt --------
Milk, 2 Litres $ 2
Potatoes $ 7.5
Sugar $ 3.5