0

我正在尝试从查询字符串中删除某些项目,最好的方法是解析查询字符串,迭代并删除我不想要的特定键并将它们重新连接在一起。

按照 python 指南,他们说要使用的 urlencode 函数似乎没有像预期的那样工作。

使用以下代码,它只是解析查询字符串,然后将其重新连接在一起。我已将其设置为保留空值。

>>> f = 'name=John%20Doe&seq=123412412412&wer'
>>> q = urlparse.parse_qs(f, keep_blank_values=True)
>>> q
{'wer': [''], 'name': ['John Doe'], 'seq': ['123412412412']}
>>> urllib.urlencode(q)
'wer=%5B%27%27%5D&name=%5B%27John+Doe%27%5D&seq=%5B%27123412412412%27%5D'

我期望查询代码的结果与 f 字符串相同。

http://docs.python.org/2/library/urlparse.html#urlparse.parse_qs

Use the urllib.urlencode() function to convert such dictionaries into query strings.

所以我假设我必须遍历 q 变量并手动构建字符串,在字典的每个项目上调用 urlencode?有没有更好的办法...

使用 python 2.7

谢谢

4

1 回答 1

1

您应该使用dosequrlencode 的参数,因为您的查询字典中有序列:

>>> urllib.urlencode(q, doseq=1)
'wer=&name=John+Doe&seq=123412412412'
于 2013-02-24T09:42:01.317 回答