调整不同长度的输出

2024-10-01 22:36:29 发布

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

我最近看到一篇关于如何对齐输出(Python: Format output string, right alignment)的帖子。关于那一页上答案的问题是没有一个回答我的问题。是的,它教会了我如何对齐单个输出而不是不同长度的输出。这是一个示例代码,向您展示我的意思:

purchasableItems = {'1234' : {'name' : 'tomato' : 'price' : 0.20}
                    '8765' : {'name' : 'mango' : 'price' : 1},
                    '5678' : {'name' : 'pineapple' : 'price' : 1}}
choice = input("Code: ") #write the items 4 digit code
amount = input("Amount: ") #how much of that item
price = int(amount) * (purchasableItems[choice]['price']
print("That would be {} {} {:>5} {:>5} {:>5}".format(choice, purchasableItems[choice]['name'], amount, purchasableItems[choice]['price'], price))

我尝试过将'{:>5}'重新排列成各种不同的数字,但它不允许我以我想要的方式打印,我希望它打印为:

^{pr2}$

当用户完成后,我希望程序输出一个收据:

Your receipt is:
1234 tomato   3   0.20   0.60
8765 mango    2   1.00   2.00

如你所见,收据排列得很整齐。在

但它实际上输出为,这取决于项目的长度

Your receipt is:
1234 tomato   3   0.20   0.60
5678 pineapple    2   1.00   2.00

为了爱我无法理解的一切


Tags: nameformatinputoutputyourisamountprice
1条回答
网友
1楼 · 发布于 2024-10-01 22:36:29

您可以使用\t输入制表符来排列打印。如果还没有排好队,你可以有一个以上。\t\t

我很难用你的代码演示这一点,因为我得到了语法错误。但下面是我的一个脚本中的一个示例:

print ("Floating Value:\t" , value)
print ("Decimal Value:\t" , finalans)

这是输出:

^{pr2}$

另一个具有多个\ts的示例:

print ("Diameter = \t\t" , 2 * radius , "cm")
print ("Circumference = \t" , 2 * radius * pi , "cm")
print ("Area = \t\t\t" , pi * radius ** 2 , "cm")

相关问题 更多 >

    热门问题