在Python 2.4中使用urllib解析查询字符串 [英] parse query string with urllib in Python 2.4

查看:147
本文介绍了在Python 2.4中使用urllib解析查询字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Python2.4.5(不要问!),我想解析一个查询字符串并获得一个dict作为回报.我是否需要像下面这样手动"进行操作?

Using Python2.4.5 (don't ask!) I want to parse a query string and get a dict in return. Do I have to do it "manually" like follows?

>>> qs = 'first=1&second=4&third=3'
>>> d = dict([x.split("=") for x in qs.split("&")])
>>> d
{'second': '4', 'third': '3', 'first': '1'}

urlparse中找不到任何有用的方法.

Didn't find any useful method in urlparse.

推荐答案

您有两个选择:

>>> cgi.parse_qs(qs)
{'second': ['4'], 'third': ['3'], 'first': ['1']}

>>> cgi.parse_qsl(qs)
[('first', '1'), ('second', '4'), ('third', '3')]

cgi.parse_qs()返回的dict中的值是列表而不是字符串,以便处理多次指定相同参数的情况:

The values in the dict returned by cgi.parse_qs() are lists rather than strings, in order to handle the case when the same parameter is specified several times:

>>> qs = 'tags=python&tags=programming'
>>> cgi.parse_qs(qs)
{'tags': ['python', 'programming']}

这篇关于在Python 2.4中使用urllib解析查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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