Joh*_*DOe 1 python string-formatting
所以我试图让美元符号直接出现在“成本”列下数字的左侧。我无法解决这个问题,任何帮助表示赞赏。
# 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))
Run Code Online (Sandbox Code Playgroud)
我还希望成本列的格式正确,但由于某种原因,在我运行程序时并非如此。
(我的输出):
如果我理解正确,您想将浮点数格式化为字符串,并在输出中出现在数字和用于在字符串中将其隔开的填充之间的美元符号。例如,您希望能够使用相同的格式代码(只是不同的值)创建这两个字符串:
foo: $1.23
foo: $12.34
Run Code Online (Sandbox Code Playgroud)
不幸的是,您不能仅通过一种字符串格式化操作来完成此操作。对数字应用填充时,填充字符将出现在数字和任何前缀文本之间,例如当前代码中的美元符号。您可能需要分两步格式化数字。首先将数字转换为以美元符号为前缀的字符串,然后再次格式化以将美元字符串插入到具有适当填充的最终字符串中。
下面是我如何生成上面的示例字符串:
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11725 次 |
| 最近记录: |