Best way to get query string from a URL in python?


I need to get the query string from this URL and I don't want to use request.META. I have figured out that there are two more ways to get the query string:

  1. Using urlparse urlparse.urlparse(url).query

  2. Using url encode Use urlencode and pass the request.GET params dictionary into it to get the string representation.

So which way is better? My colleagues prefer urlencode but have not provided a satisfying explanation. They claim that urlparse calls urlencode internally which is something I'm not sure about since urlencode lives in the urllib module.

12/4/2018 10:36:20 AM

Accepted Answer

You can make Query string using GET parameters like this


This does not include the ? prefix, and it may not return the keys in the same order as in the original request.

1/5/2017 1:37:26 PM

Third option:

>>> from urlparse import urlparse, parse_qs
>>> url = ''
>>> urlparse(url).query
>>> parse_qs(urlparse(url).query)
{'blah': ['1'], 'x': ['2']}

In Python 3+ this is available as:

from urllib.parse import parse_qs

Documentation for urllib.parse

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow