Question

How can I encode a string so that I can pass the encoded string in url params?

Was it helpful?

Solution

use urllib.quote_plus function. Here is an example:

#!/usr/bin/python

print "Content-Type: text/html;charset=utf-8";
print

import urllib

str = "Hello World?"
str = urllib.quote_plus(str)

print str

Output: Hello+World%3F

OTHER TIPS

The library too use is urllib, see http://docs.python.org/2/library/urllib.html

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

>>> urllib.quote_plus('string_of_characters_like_these:$#@=?%^Q^$')
'string_of_characters_like_these%3A%24%23%40%3D%3F%25%5EQ%5E%24'

Use urllib.encode()

>>> import urllib
>>> f = { 'eventName' : 'myEvent', 'eventDescription' : "cool event"}
>>> urllib.urlencode(f)
'eventName=myEvent&eventDescription=cool+event'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top