ValueError: unsupported format character while forming strings

42

This works:

print "Hello World%s" %"!"

But this doesn't

print "Hello%20World%s" %"!"

the error is ValueError: unsupported format character 'W' (0x57) at index 8

I am using Python 2.7.

Why would I do this? Well %20 is used in place of spaces in urls, and if use it, I can't form strings with the printf formats. But why does Python do this?

This question is tagged with python

~ Asked on 2012-01-13 20:00:39

The Best Answer is


70

You could escape the % in %20 like so:

print "Hello%%20World%s" %"!"

or you could try using the string formatting routines instead, like:

print "Hello%20World{0}".format("!")

http://docs.python.org/library/string.html#formatstrings

~ Answered on 2012-01-13 20:09:49


16

You could escape the % with another % so %%20

This is a similar relevant question Python string formatting when string contains "%s" without escaping

~ Answered on 2012-01-13 20:03:53


Most Viewed Questions: