字符串格式化美元符号 Python

String Formatting Dollar Sign In Python

所以我试图让美元符号直接出现在 'Cost' 列下数字的左侧。我无法解决这个问题,我们将不胜感激。

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

我还希望成本列的格式正确,但出于某种原因,当我 运行 程序时它不是。

(我的输出):

编辑:我也无法将“$”格式化为成本,因为我必须在格式中保留 2 位小数

如果我没理解错的话,你想将一个浮点数格式化为一个字符串,并在数字和你用来 space 的填充之间的输出中出现一个美元符号字符串。例如,您希望能够使用相同的格式代码(只是不同的值)创建这两个字符串:

foo:    .23
foo:   .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)