Python – Prepare a string for Google Ajax Search

google apigoogle-ajax-apipythonurl

I have strings such as

["Tabula Rasa", "façade", "DJ Tiësto"]

I'm accessing Google Ajax API in Python using the base url:

base = 'http://ajax.googleapis.com/ajax/services/search/web'
   '?v=1.0&q=%s'

I'm having issues using these strings plain and noticed I have to transform certain characters,

eg. "Tabula Rasa" -->  "Tabula%20Rasa"

But I have a huge list of these strings and I do not know of a way I can automatically prepare these string for the URL query.

Any help would be very much appreciated.

Best Answer

What you're looking for is urllib.quote():

>>> urllib.quote("Tabula Rasa")
'Tabula%20Rasa'

The non-ASCII strings may need to be recoded into the encoding expected by the Google AJAX API, if you don't have them in the same encoding already.