格式不受支持的字符?

时间:2015-06-30 04:53:04

标签: python python-2.7

我正在尝试使用带有浮动格式化程序的行打印到2个小数点,如下所示:

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

但是当我这样做时,我收到了这个错误:

ValueError:索引27处的格式字符'a'(0x61)不受支持

这意味着什么?如何防止它发生?

3 个答案:

答案 0 :(得分:4)

问题在于您的20%,Python正在将...20% and...作为"% a" % price阅读,并且它不会将%a识别为格式。

您可以使用20%%作为@Anand指出,或者您可以使用字符串.format()

>>> 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一样为您提供2位小数。

答案 1 :(得分:2)

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

试试这个 -

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

答案 2 :(得分:0)

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

%之后的%并非如此,因此必须正确转义:写20。这告诉格式说明符处理例程将其视为文字20%%

或者,正如Scott所写,使用较新的%内容。

相关问题