简体   繁体   中英

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

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)

First of all if you want to print % you need to do it like this

%% --> escapes the % literal character

every other combinations will be treated as formatted characters. for example %c is treated as a single character, represented as a C int.

Please refer to the link here

To escape the % in python, just use %% , in your example, the following will give the result you want,

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

Or you could use string's format method which is preferred in python 3 and also available in python 2.7

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

One tip for you to transit from % style formatting to string's format method, AFAIK, all % format letters remain the same used in string's format method. This means "%s" % "lat" would simply become "{0:s}".format("lat") , "%d" % 3 to "{0:d}".format(3) , and etc. Notice the 0 here. It indicates which parameter in the format method is formatted, with first parameter indexed as 0.

See more details here on the official documentation about python string's format method

aside from % escape. you can also add the '%' in the 'lat' before passing it or just add another '%s' for '%'

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

im just giving you another option.but %% escape is the best choice

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM