在python中如何在同一行中打印两个空格相等的单词

2024-09-28 21:54:46 发布

您现在位置:Python中文网/ 问答频道 /正文

-------- Final Receipt --------
Milk, 2 Litres $ 2
Potatoes $ 7.5
Sugar $ 3.5

我希望这份打印报表

 -------- 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])

产品列表中的产品是嵌套字典

代码是完全工作,但需要我的输出风格


Tags: infor报表产品productzipsugarlist
2条回答

您可能希望使用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

您可以使用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

相关问题 更多 >