0

I am trying to remove certain items from a query string, the best way doing this would be to parse the query string, iterate over and remove the particular key I dont want and join it all back together.

Following the python guide, it seems the urlencode function they say to use, doesn't work as one would expect.

Fee the following code, which simply parses the query string, and then joins it back together. I've set it to keep the empty value.

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

I am expecting the result of the query code, to be the same as the f string.

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

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

So I assume I have to loop over the q variable and build the string manually, calling urlencode on each item of the dictionary? Isn't there a better way...

Using python 2.7

Thanks

1 Answer 1

1

You should use the doseq argument to urlencode since you have sequences in your query dict:

>>> urllib.urlencode(q, doseq=1)
'wer=&name=John+Doe&seq=123412412412'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.