[英]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
错误是
ValueError: unsupported format character 'W' (0x57) at index 8
I am using Python 2.7.我正在使用 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.嗯
%20
用于代替 url 中的空格,如果使用它,我无法使用 printf 格式形成字符串。 But why does Python do this?但是为什么 Python 会这样做呢?
You could escape the % in %20 like so:您可以像这样转义 %20 中的 % :
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 http://docs.python.org/library/string.html#formatstrings
You could escape the % with another % so %%20
你可以用另一个 % 来转义 % 所以
%%20
This is a similar relevant question Python string formatting when string contains "%s" without escaping这是一个类似的相关问题Python 字符串格式,当字符串包含“%s”而不转义时
你可能有错别字.. 就我而言,我说的是 %w,而我本想说的是 %s。
I was using python interpolation and forgot the ending s
character:我正在使用 python 插值并忘记了结尾的
s
字符:
a = dict(foo='bar')
print("What comes after foo? %(foo)" % a) # Should be %(foo)s
Watch those typos.注意那些错别字。
Well, why do you have %20
url-quoting escapes in a formatting string in first place?那么,为什么首先在格式化字符串中有
%20
url 引用转义? 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:然后你在 url 之后引用它:
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.这更好,因为它会引用字符串中所有 url 可引用的内容,包括
text
部分中的text
。
For anyone checking this using python 3:对于使用 python 3 进行检查的任何人:
If you want to print the following output "100% correct"
:如果要打印以下输出
"100% correct"
:
python 3.8: print("100% correct")
python 3.8:
print("100% correct")
python 3.7 and less: print("100%% correct")
python 3.7 及更低版本:
print("100%% correct")
A neat programming workaround for compatibility across diff versions of python is shown below:下面显示了一种用于跨不同版本的 python 兼容性的简洁编程解决方法:
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.
注意:如果您必须使用它,您可能会遇到许多其他错误......我鼓励您在相关机器上升级/降级 python,以便它们都兼容。
DevOps is a notable exception to the above -- implementing the following code would indeed be appropriate for specific DevOps / Debugging scenarios.DevOps 是上述情况的一个显着例外——实现以下代码确实适用于特定的 DevOps/调试场景。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.