简体   繁体   English

如何从parse_qsl更改python中参数的值?

[英]How to change a value in a parameter in python from parse_qsl?

I need to add +four to the parameter q and unparse the query string after making the modification. 我需要在参数q上添加+ four并在进行修改后取消解析查询字符串。 The problem I'm having is parse_qsl gives tuples in a list so I can't modify the tuple. 我遇到的问题是parse_qsl在列表中提供了元组,因此我无法修改元组。 I can't use parse_qs because I have multiple parameters with the same name. 我不能使用parse_qs,因为我有多个具有相同名称的参数。 How do I modify q parameter and unparse the query in this scenario? 在这种情况下,如何修改q参数并取消解析查询?

from urllib import parse
url = 'https://www.test.com/search?q=one+two+three&array[]=apple&array[]=oranges'
parts = parse.urlparse(url)
querys = parse.parse_qsl(parts.query)

# >>> querys
# [('q', 'one two three'), ('array[]', 'apple'), ('array[]', 'oranges')]

I'm not sure I understood your question correctly, is this what you want? 我不确定我是否正确理解了您的问题,这是您想要的吗?

from urllib import parse

url = 'https://www.test.com/search?q=one+two+three&array[]=apple&array[]=oranges'
parts = parse.urlparse(url)
querys = [list(q) for q in parse.parse_qsl(parts.query)]

for q in querys:
    if q[0] == 'q':
        q[1] = q[1] + ' four'

print([tuple(q) for q in querys])
#[('q', 'one two three four'), ('array[]', 'apple'), ('array[]', 'oranges')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM