urllib – How to urlencode a querystring in Python?

urllib – How to urlencode a querystring in Python?

Python 2

What youre looking for is urllib.quote_plus:

safe_string = urllib.quote_plus(string_of_characters_like_these:$#@=?%^Q^$)

#Value: string_of_characters_like_these%3A%24%23%40%3D%3F%25%5EQ%5E%24

Python 3

In Python 3, the urllib package has been broken into smaller components. Youll use urllib.parse.quote_plus (note the parse child module)

import urllib.parse
safe_string = urllib.parse.quote_plus(...)

You need to pass your parameters into urlencode() as either a mapping (dict), or a sequence of 2-tuples, like:

>>> import urllib
>>> f = { eventName : myEvent, eventDescription : cool event}
>>> urllib.urlencode(f)

Python 3 or above


>>> urllib.parse.urlencode(f)

Note that this does not do url encoding in the commonly used sense (look at the output). For that use urllib.parse.quote_plus.

urllib – How to urlencode a querystring in Python?

Try requests instead of urllib and you dont need to bother with urlencode!

import requests
requests.get(http://youraddress.com, params=evt.fields)


If you need ordered name-value pairs or multiple values for a name then set params like so:

params=[(name1,value11), (name1,value12), (name2,value21), ...]

instead of using a dictionary.

Leave a Reply

Your email address will not be published. Required fields are marked *