简体   繁体   中英

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. The problem I'm having is parse_qsl gives tuples in a list so I can't modify the tuple. I can't use parse_qs because I have multiple parameters with the same name. How do I modify q parameter and unparse the query in this scenario?

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')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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