Dean Christian Armada Dean Christian Armada - 1 month ago 11
Python Question

Python string percent sign escape

I am experimenting some string outputs and I came across something that throws an error when printing

x = "ll=%s%2C%20%s" % ("lat", "lng")


The syntax above throws an error:

ValueError: unsupported format character 'C' (0x43) at index 7


What am I missing here? I wish to have a result of:

ll=lat%2C%20lang


With the use of %s operators on concatenating a variable inside a string

Answer

When python sees that %, it's expecting a formatting symbol right afterwards. Basically, it expects something like %s or %d... But it finds a C, and it doesn't know what to do with that.

You can see what can you put after the % in this link.

If you want to have literally % in your string you have to escape it with another %:

>>> x = "ll=%s%%2C%%20%s" % ("lat", "lng")
>>> x
'll=lat%2C%20lng'

Note that in Python 3, this way is considered "outdated" in favor of the newer .format() method. You can also use that one in Python 2.7 (I believe, though I'm not sure that it was introduced in Python 2.6 ?) and do the same like this:

>>> x = "ll={0}%2C%20{1}".format("lat", "lng")
>>> x
'll=lat%2C%20lng'

Or you could do even fancier things:

>>> x = "ll={latitude}%2C%20{longitude}".format(latitude="lat", longitude="lng")
>>> x
'll=lat%2C%20lng'

Check it out! (also, there's a Reddit thread about it)

Comments