UrlEncode in Python

Tue, Nov 3, 2009

Tech Tips

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

  1. use urllib  
  2. # you have to pass in a dictionary  
  3. print urllib.urlencode({'id':'100''name':'john smith'})  
  4.   
  5. # then you get 'id=100&name=john+smith'  

Urlencoding Unicode and UTF8 Values

  1. #this works fine  
  2. print urllib.urlencode({name:'José'})  
  3.   
  4. #you have to be careful with unicode strings  
  5. # this will throw an error:  
  6. print urllib.urlencode({name:u'José'})  
  7. # UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in   
  8. # position 11: ordinal not in range  
  9.   
  10. #since the default ascii conversion can't handle the 'é',  
  11. # you have to be explicit in what charset you are using  
  12. 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…