我正在尝试使用带有浮点格式器的行将行打印到2个小数点,如下所示:
print "You have a discount of 20% and the final cost of the item is'%.2f' dollars." % price
Run Code Online (Sandbox Code Playgroud)
但是当我这样做时,会出现以下错误:
ValueError:索引27处不支持的格式字符'a'(0x61)
这是什么意思,我该如何防止它发生?
问题是你的20%,Python是阅读...20% and...作为"% a" % price和不承认%a的格式。
您可以20%%像@Anand 指出的那样使用,也可以使用 string .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.
Run Code Online (Sandbox Code Playgroud)
此处:.2f为您提供 2 个小数位%.2f。
我认为问题在于%后面的单号20,python 可能认为它是格式说明符。
尝试这个 -
print "You have a discount of 20%% and the final cost of the item is'%.2f' dollars." % price
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7985 次 |
| 最近记录: |