UrlEncode in Python

Tue, Nov 3, 2009

Tech Tips

To urlencode a querystring or form data in python you can use the urllib module:

use urllib
# you have to pass in a dictionary
print urllib.urlencode({'id':'100', 'name':'john smith'})

# then you get 'id=100&name=john+smith'

Urlencoding Unicode and UTF8 Values

#this works fine
print urllib.urlencode({name:'José'})

#you have to be careful with unicode strings
# this will throw an error:
print urllib.urlencode({name:u'José'})
# UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in 
# position 11: ordinal not in range

#since the default ascii conversion can't handle the 'é',
# you have to be explicit in what charset you are using
print urllib.urlencode({'name':u'José'.encode('utf8')})

Additional Info:
Python Doc for urllib module
Unicode Primer

Bookmark and Share

2 Responses to “UrlEncode in Python”

  1. audio codecs download Says:

    Thanks for the shortest one. I always believe If somebody able to understand a code, they always come up with a much simplest one. I’m happy that someone other than me can able to understand my script :).

  2. Lingodb Says:

    Thanks! I can’t understand why Python still has these issues with unicode…