Python 将列表中的空格转换为 %20
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27556134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert spaces to %20 in list
提问by user2363318
I need to convert spaces to %20 for api posts in a python array
我需要将空格转换为 %20 以用于 python 数组中的 api 帖子
tree = et.parse(os.environ['SPRINT_XML'])
olp = tree.findall(".//string")
if not olp:
print colored('FAILED', 'red') +" No jobs accociated to this view"
exit(1)
joblist = [t.text for t in olp]
How can I do that to t.text above?
我怎样才能对上面的 t.text 做到这一点?
采纳答案by mbomb007
Use the String.replace()
method as described here: http://www.tutorialspoint.com/python/string_replace.htm
使用String.replace()
此处描述的方法:http: //www.tutorialspoint.com/python/string_replace.htm
So for t.text
, it would be t.text.replace(" ", "%20")
所以对于t.text
,这将是t.text.replace(" ", "%20")
回答by zmbq
Use urllib.quote_plusfor this:
为此使用urllib.quote_plus:
import urllib
...
joblist = [urllib.quote_plus(t.text) for t in olp]
回答by Jan Rozycki
I would recommend using urllib.parse
module and its quote()
function.
https://docs.python.org/3.6/library/urllib.parse.html#urllib.parse.quoteExample for Python3:
我建议使用urllib.parse
模块及其quote()
功能。
https://docs.python.org/3.6/library/urllib.parse.html#urllib.parse.quotePython3 示例:
from urllib.parse import quote
text_encoded = quote(t.text)
Note: using quote_plus()
won't work in your case as this function replaces spaces by plus char.
注意: usingquote_plus()
在您的情况下不起作用,因为此函数用加字符替换空格。