python中print语句中的异常

Jar*_*vis 0 python

假设我print在python中有一个语句给出:

print "components required to explain 50% variance : %d" % (count)
Run Code Online (Sandbox Code Playgroud)

这个陈述给出了一个ValuError,但如果我有这个print陈述:

print "components required to explain 50% variance"
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

mgi*_*son 7

错误消息在这里非常有用:

>>> count = 10
>>> print "components required to explain 50% variance : %d" % (count)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: unsupported format character 'v' (0x76) at index 35
Run Code Online (Sandbox Code Playgroud)

所以python看到% v并认为它是格式代码.但是,v它不是受支持的格式字符,因此会引发错误.

一旦你知道它,修复就很明显了 - 你需要转义%不属于格式代码的s.你是怎样做的?添加另一个%:

>>> print "components required to explain 50%% variance : %d" % (count)
components required to explain 50% variance : 10
Run Code Online (Sandbox Code Playgroud)

请注意,.format在很多情况下,您也可以使用哪个更方便,更强大:

>>> print "components required to explain 50% variance : {:d}".format(count)
components required to explain 50% variance : 10
Run Code Online (Sandbox Code Playgroud)