Convert spaces to %20 in list

会有一股神秘感。 提交于 2020-05-12 11:59:32

问题


I need to convert spaces to %20 for api posts in a python array

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?


回答1:


Use the String.replace() method as described here: http://www.tutorialspoint.com/python/string_replace.htm

So for t.text, it would be t.text.replace(" ", "%20")




回答2:


I would recommend using urllib.parse module and its quote() function. https://docs.python.org/3.6/library/urllib.parse.html#urllib.parse.quote Example for Python3:

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.




回答3:


Use urllib.quote_plus for this:

import urllib

...

joblist = [urllib.quote_plus(t.text) for t in olp]


来源:https://stackoverflow.com/questions/27556134/convert-spaces-to-20-in-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!