因此,我试图使美元符号直接显示在“费用”列下数字的左侧。我在弄清楚这一点时遇到了麻烦,感谢您的帮助。
# Question 5
print("\nQuestion 5.")
# Get amount of each type of ticket to be purchased
adultTickets = input("\nHow many adult tickets you want to order: ")
adultCost = int(adultTickets) * 50.5
childTickets = input("How many children (>=10 years old) tickets: ")
childCost = int(childTickets) * 10.5
youngChildTickets = input("How many children (<10 years old) tickets: ")
# Display ticket info
print ("\n{0:<17} {1:>17} {2:>12}".format("Type", "Number of tickets",
"Cost"))
print ("{0:<17} {1:>17}${2:>12.2f}".format("Adult", adultTickets, adultCost))
print ("{0:<17} {1:>17}${2:>12.2f}".format("Children (>=10)", childTickets,
childCost))
print ("{0:<17} {1:>17} {2:>12}".format("Children (<10)", youngChildTickets,
"free"))
#Calculate total cost and total amount of tickets
totalTickets = (int(adultTickets) + int(childTickets) +
int(youngChildTickets))
totalCost = adultCost + childCost
print ("{0:<17} {1:>17}${2:>12.2f}".format("Total", totalTickets, totalCost))
我也希望cost列的格式正确,出于某种原因,当我运行程序时,它不是。
(我的输出):
如果我的理解正确,您想将浮点数格式化为字符串,并在数字和用来在字符串中隔开空格的填充之间的输出中出现美元符号。例如,您希望能够使用相同的格式代码(只是值不同)创建这两个字符串:
foo: $1.23
foo: $12.34
[不幸的是,您不能仅通过一个字符串格式化操作来执行此操作。当您对数字应用填充时,填充字符将出现在数字和任何带前缀的文本之间,例如当前代码中的美元符号。您可能需要分两步设置数字格式。首先将数字放入带有美元符号前缀的字符串中,然后再次格式化以将美元字符串插入具有适当填充的最终字符串中。
这是我上面产生示例字符串的方式:
a = 1.23
b = 12.34
a_dollars = "${:.2f}".format(a) # make strings with leading dollar sign
b_dollars = "${:.2f}".format(b)
a_padded = "foo:{:>8}".format(a_dollars) # insert them into strings with padding
b_padded = "foo:{:>8}".format(b_dollars)