【问题标题】:Aligning outputs of different lengths对齐不同长度的输出
【发布时间】:2017-03-12 18:56:30
【问题描述】:

我最近看到一篇关于如何对齐输出的帖子 (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}' 重新排列成各种其他数字,但它不允许我按照我想要的方式打印,我希望它打印为:

Code: 1234
Amount: 3
That would be: 1234 tomato    3   0.20    0.60
Code: 8765
Amount: 2
That would be: 8765 mango     2   1.00    2.00

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

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

对于任何我想不通的事情的热爱

【问题讨论】:

  • 看看这个答案是否有帮助:stackoverflow.com/questions/40321732/…
  • 抱歉回复晚了,但很遗憾没有回答我的问题
  • 当您尝试使代码适应您的目的时会发生什么?
  • 以这种方式输出:Your receipt is: 1234 tomato 3 0.20 0.60 8765 mango 2 1.00 2.00' unaligned. The difference is much more clear to see in examples such as: 您的收据是:1234 番茄 3 0.20 0.60 8765 菠萝 2 1.00 2.00`
  • 不幸的是,它在 cmets 中显示不正确,所以我编辑了我的帖子

标签: python list dictionary


【解决方案1】:

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

由于出现语法错误,我无法用您的代码演示这一点。但这是我的一个脚本中的一个示例:

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

这是输出:

Floating Value:  010000111111101101
Decimal Value:   123.25

另一个有多个\ts 的例子:

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

【讨论】:

  • 看不懂,能不能举个例子
  • 我很抱歉。我试图让它与你的代码一起工作,但有问题。请参阅编辑以获取我的一个程序中的示例。
  • 抱歉回复晚了,可惜那个方法不行
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-30
  • 2020-02-18
相关资源
最近更新 更多