51

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?

highBandWidth
  • 16,751
  • 20
  • 84
  • 131

6 Answers6

80

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

jgritty
  • 11,660
  • 3
  • 38
  • 60
17

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

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

Community
  • 1
  • 1
dm03514
  • 54,664
  • 18
  • 108
  • 145
8

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

Alan Viars
  • 3,112
  • 31
  • 14
8

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.

NuclearPeon
  • 5,743
  • 4
  • 44
  • 52
4

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.

nosklo
  • 217,122
  • 57
  • 293
  • 297
0

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"
    else:
        my_string = "100%% correct"

# Finally
print(my_string)
Yaakov Bressler
  • 9,056
  • 2
  • 45
  • 69