[英]Parsing a list into a url string
I have a list of tags that I would like to add to a url string, separated by commas ('%2C'). 我有一个要添加到url字符串的标签列表,以逗号('%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
? 还需要将逗号更改为
%2C
吗? I need it to feedpaarser to parse results. 我需要它来feedpaarser解析结果。 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
? 但是我可以逃脱此
%2C
吗? Also I'm pretty sure there is a shorter 'lambda' way :) 我也很确定会有一个较短的“ lambda”方式:)
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, eg: 展望未来,我认为您想使用
format()
进行字符串插值,例如:
>>> 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'
"%s"
is fine, but urlparse.urlunparse
after urllib.urlencode
is safer. "%s"
可以,但urllib.urlencode
之后的urlparse.urlunparse
更安全。
str.join
is fine, but remember to check your tags for commas and number signs, or use urllib.quote
on each one. str.join
很好,但是请记住检查标记中的逗号和数字符号,或者在每个urllib.quote
上使用urllib.quote
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.