从 Python 3 中的查询字符串中获取值,而不在值中显示 [' ']

Get value from query string in Python 3 without the [' '] showing up in the value

我在Python3http服务器中有如下代码解析出一个URL然后解析出一个查询字符串:

parsedURL = urlparse(self.path)
parsed = parse_qs(parsedURL.query)

parsedURL.query 在这种情况下变成 x=7&=3。我想把 7 和 3 拿出来并设置它们等于变量 x 和 y。我都试过了

x = parsed['x']
y = parsed['y']

x = parsed.get('x')
y = parsed.get('y')

这两个解决方案都提出了 x = ['7'] 和 y = ['3'] 但我不想要括号和单引号,我想要 just73,我希望它们是整数。如何获取值并摆脱 brackets/quotes?

只会:

x = int(parsed['x'][0])
y = int(parsed['y'][0])

x = int(parsed.get('x')[0])
y = int(parsed.get('y')[0])

达到你的目的?您当然应该进行适当的验证检查,但您要做的只是将返回数组的第一个元素转换为 int,因此这段代码将完成这项工作。

这是因为 get() returns 值数组(我猜!)所以如果你尝试解析 url?x=1&x=2&x=foo 你会得到像 ['1', '2', 'foo'] 这样的列表.通常查询字符串中的每个变量只有一个(当然是零个)实例,因此我们只需使用 [0].

获取第一个条目

注意 documentation for parse_qs() 说:

Data are returned as a dictionary. The dictionary keys are the unique query variable names and the values are lists of values for each name.