Parsing a list into a url string

孤街浪徒 提交于 2019-12-13 01:57:16

问题


I have a list of tags that I would like to add to a url string, separated by commas ('%2C'). How can I do this ? I was trying :

>>> tags_list
['tag1', ' tag2']
>>> parse_string = "http://www.google.pl/search?q=%s&restofurl" % (lambda x: "%s," %x for x in tags_list)

but received a generator :

>>> parse_string
'http://<generator object <genexpr> at 0x02751F58>'

Also do I need to change commas to %2C? I need it to feedpaarser to parse results. If yes - how can I insert those tags separated by this special sign ?


EDIT:

parse_string = ""
for x in tags_list:
    parse_string += "%s," % x

but can I escape this %2C ? Also I'm pretty sure there is a shorter 'lambda' way :)


回答1:


parse_string = ("http://www.google.pl/search?q=%s&restofurl" % 
               '%2C'.join(tag.strip() for tag in tags_list))

Results in:

>>> parse_string = ("http://www.google.pl/search?q=%s&restofurl" %
...                '%2C'.join(tag.strip() for tag in tags_list))
>>> parse_string
'http://www.google.pl/search?q=tag1%2Ctag2&restofurl'

Side note:
Going forward I think you want to use format() for string interpolation, e.g.:

>>> parse_string = "http://www.google.pl/search?q={0}&restofurl".format(
...                '%2C'.join(tag.strip() for tag in tags_list))
>>> parse_string
'http://www.google.pl/search?q=tag1%2Ctag2&restofurl'



回答2:


"%s" is fine, but urlparse.urlunparse after urllib.urlencode is safer.

str.join is fine, but remember to check your tags for commas and number signs, or use urllib.quote on each one.



来源:https://stackoverflow.com/questions/3984422/parsing-a-list-into-a-url-string

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