2024-05-14 10:56:21 发布
网友
我正试图用浮点格式化程序将一行打印到2个小数点,如下所示:
print "You have a discount of 20% and the final cost of the item is'%.2f' dollars." % price
但当我这样做的时候,我得到了这个错误:
值错误:索引27处不支持的格式字符“a”(0x61)
这是什么意思?我怎样才能防止它发生?
字符串上的%运算符将其左操作数视为格式说明符。它中的所有%符号都将被特殊处理。
%
但是20后面的%不是这样的,因此必须正确转义:write20%%。这告诉格式说明符处理例程将其视为文本%。
20
20%%
或者,正如Scott所写,使用较新的.format()内容。
.format()
问题是您的20%,Python正在将...20% and...读取为"% a" % price,它不将%a识别为格式。
20%
...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。
:.2f
%.2f
我认为问题在于%之后的单个20符号,python可能认为它是一个格式说明符。
试试这个-
print "You have a discount of 20%% and the final cost of the item is'%.2f' dollars." % price
字符串上的
%
运算符将其左操作数视为格式说明符。它中的所有%
符号都将被特殊处理。但是
20
后面的%
不是这样的,因此必须正确转义:write20%%
。这告诉格式说明符处理例程将其视为文本%
。或者,正如Scott所写,使用较新的
.format()
内容。问题是您的
20%
,Python正在将...20% and...
读取为"% a" % price
,它不将%a
识别为格式。您可以使用@Anand指出的} :
20%%
,也可以使用字符串^{这里的
:.2f
给您两个小数位,就像%.2f
。我认为问题在于
%
之后的单个20
符号,python可能认为它是一个格式说明符。试试这个-
相关问题 更多 >
编程相关推荐