0

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 ?

Jarvis
  • 8,020
  • 3
  • 23
  • 51

2 Answers2

7

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
mgilson
  • 264,617
  • 51
  • 541
  • 636
4

The % operator, applied to strings, performs a substitution for every '%' in the string. '50%' does not specify a valid substitution; to simply include a percent sign in the string, you have to double it.

jasonharper
  • 8,782
  • 2
  • 15
  • 38