Jarvis Jarvis - 14 days ago 4
Python Question

Anomaly in print statement in python

Suppose I have a

print
statement in python as given :

print "components required to explain 50% variance : %d" % (count)


This statement gives a
ValuError
, but if I have this
print
statement :

print "components required to explain 50% variance"


Why does this happen ?

Answer

The error message is pretty helpful here:

>>> 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

So python sees % v and it thinks that it is a format code. However, v isn't a supported format character so it raises an error.

The fix is obvious once you know it -- You need to escape the %s that aren't part of a format code. How do you do that? By adding another %:

>>> print "components required to explain 50%% variance : %d" % (count)
components required to explain 50% variance : 10

Note that you could also use .format which is more convenient and powerful in a lot of circumstances:

>>> print "components required to explain 50% variance : {:d}".format(count)
components required to explain 50% variance : 10
Comments