ValueError:形成字符串时不支持的格式字符

hig*_*dth 36 python

这有效:

print "Hello World%s" %"!"
Run Code Online (Sandbox Code Playgroud)

但事实并非如此

print "Hello%20World%s" %"!"
Run Code Online (Sandbox Code Playgroud)

错误是 ValueError: unsupported format character 'W' (0x57) at index 8

我使用的是Python 2.7.

我为什么要这样做?好%20用于代替网址中的空格,如果使用它,我不能用printf格式形成字符串.但为什么Python会这样做呢?

jgr*_*tty 61

你可以像这样逃避%20中的%:

print "Hello%%20World%s" %"!"
Run Code Online (Sandbox Code Playgroud)

或者您可以尝试使用字符串格式化例程,例如:

print "Hello%20World{0}".format("!")
Run Code Online (Sandbox Code Playgroud)

http://docs.python.org/library/string.html#formatstrings


dm0*_*514 13

您可以使用另一个%来逃避% %%20

当字符串包含"%s"而没有转义时,这是一个类似的相关问题Python字符串格式


Nuc*_*eon 8

我正在使用 python 插值并忘记了结束s字符:

a = dict(foo='bar')
print("What comes after foo? %(foo)" % a) # Should be %(foo)s
Run Code Online (Sandbox Code Playgroud)

注意那些错别字。


Ala*_*ars 5

您可能有错字。.在我的情况下,我说的是%w,我的意思是说%s。