Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValueError: unsupported format character while forming strings

Tags:

python

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?

like image 542
highBandWidth Avatar asked Jan 13 '12 20:01

highBandWidth


4 Answers

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

like image 187
jgritty Avatar answered Nov 19 '22 15:11

jgritty


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

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

like image 41
dm03514 Avatar answered Nov 19 '22 17:11

dm03514


I was using python interpolation and forgot the ending s character:

a = dict(foo='bar')
print("What comes after foo? %(foo)" % a) # Should be %(foo)s

Watch those typos.

like image 8
NuclearPeon Avatar answered Nov 19 '22 16:11

NuclearPeon


You might have a typo.. In my case I was saying %w where I meant to say %s.

like image 7
Alan Viars Avatar answered Nov 19 '22 17:11

Alan Viars