ValueError: unsupported format character while forming strings


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?

Asked By: highBandWidth



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

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

Answered By: dm03514

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("!")

Answered By: jgritty

Well, why do you have %20 url-quoting escapes in a formatting string in first place? Ideally you’d do the interpolation formatting first:

formatting_template = 'Hello World%s'
text = '!'
full_string = formatting_template % text

Then you url quote it afterwards:

result = urllib.quote(full_string)

That is better because it would quote all url-quotable things in your string, including stuff that is in the text part.

Answered By: nosklo

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

Answered By: Alan Viars

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.

Answered By: NuclearPeon

For anyone checking this using python 3:

If you want to print the following output "100% correct":

python 3.8: print("100% correct")
python 3.7 and less: print("100%% correct")

A neat programming workaround for compatibility across diff versions of python is shown below:

Note: If you have to use this, you’re probably experiencing many other errors… I’d encourage you to upgrade / downgrade python in relevant machines so that they are all compatible.

DevOps is a notable exception to the above — implementing the following code would indeed be appropriate for specific DevOps / Debugging scenarios.

import sys

if version_info.major==3:
    if version_info.minor>=8:
        my_string = "100% correct"
        my_string = "100%% correct"

# Finally
Answered By: Yaakov Bressler
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.