HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCriticalCanonical

How to urlencode a querystring in Python?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
urlencodehowpythonquerystring

Problem

I am trying to urlencode this string before I submit.

queryString = 'eventName=' + evt.fields["eventName"] + '&' + 'eventDescription=' + evt.fields["eventDescription"];

Solution

Python 3

Use urllib.parse.urlencode:

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


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

Python 2

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

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

Code Snippets

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

Context

Stack Overflow Q#5607551, score: 756

Revisions (0)

No revisions yet.