将列表解析为url字符串 [英] Parsing a list into a url string

查看:57
本文介绍了将列表解析为url字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,我想添加到URL字符串中,并用逗号('%2C')分隔.我怎样才能做到这一点 ?我在尝试:

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)

但收到了发电机:

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

我还需要将逗号更改为%2C 吗?我需要它来feedpaarser解析结果.如果是,如何插入由特殊符号分隔的标签?

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 ?

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

但是我可以逃脱此%2C 吗?我也很确定还有一种更短的"lambda"方式:)

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

推荐答案

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

旁注:
展望未来,我认为您想使用 format() 用于字符串插值,例如:

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'

这篇关于将列表解析为url字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆