不支持的格式字符?

2024-05-14 10:56:21 发布

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

我正试图用浮点格式化程序将一行打印到2个小数点,如下所示:

    print "You have a discount of 20% and the final cost of the item is'%.2f' dollars." % price

但当我这样做的时候,我得到了这个错误:

值错误:索引27处不支持的格式字符“a”(0x61)

这是什么意思?我怎样才能防止它发生?


Tags: andofthe程序youhave错误discount
3条回答

字符串上的%运算符将其左操作数视为格式说明符。它中的所有%符号都将被特殊处理。

但是20后面的%不是这样的,因此必须正确转义:write20%%。这告诉格式说明符处理例程将其视为文本%

或者,正如Scott所写,使用较新的.format()内容。

问题是您的20%,Python正在将...20% and...读取为"% a" % price,它不将%a识别为格式。

您可以使用@Anand指出的20%%,也可以使用字符串^{}

>>> price = 29.99
>>> print "You have a discount of 20% and the final cost of the item is {:.2f} dollars.".format(price)
You have a discount of 20% and the final cost of the item is 29.99 dollars.

这里的:.2f给您两个小数位,就像%.2f

我认为问题在于%之后的单个20符号,python可能认为它是一个格式说明符。

试试这个-

print "You have a discount of 20%% and the final cost of the item is'%.2f' dollars." % price

相关问题 更多 >

    热门问题