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
July 18th, 2010 at 8:42 am
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 :).
February 28th, 2011 at 11:58 am
Thanks! I can’t understand why Python still has these issues with unicode…