0

I'm new to python and would like some assistance.

I have a variable

q = request.GET['q']

How do I insert the variable q inside this:

url = "http://search.com/search?term="+q+"&location=sf"

Now I'm not sure what the convention is? I'm used to PHP or javascript, but I'm learning python and how do you insert a variable dynamically?

Toon Krijthe
  • 52,876
  • 38
  • 145
  • 202
hellomello
  • 8,219
  • 39
  • 151
  • 297

3 Answers3

5

Use the format method of String:

url = "http://search.com/search?term={0}&location=sf".format(q)

But of course you should URL-encode the q:

import urllib
...
qencoded = urllib.quote_plus(q)
url = 
  "http://search.com/search?term={0}&location=sf".format(qencoded)
craigmj
  • 4,827
  • 2
  • 18
  • 22
  • I've also seen sometimes using %? Why the difference? Thanks! – hellomello Sep 27 '12 at 06:36
  • You could use the % approach, but it's the 'old' approach : `url = "http://...?term=%s&location=s" % (qencoded,)` For a full discussion see http://stackoverflow.com/questions/5082452/python-string-formatting-vs-format – craigmj Sep 27 '12 at 13:48
2

One way to do it is using urllib.urlencode(). It accepts a dictionary(or associative array or whatever you call it) taking key-value pairs as parameter and value and you can encode it to form urls

    from urllib import urlencode  
    myurl = "http://somewebsite.com/?"  
    parameter_value_pairs = {"q":"q_value","r":"r_value"}  
    req_url = url +  urlencode(parameter_value_pair)

This will give you "http://somewebsite.com/?q=q_value&r=r_value"

Emil
  • 370
  • 1
  • 5
2
q = request.GET['q']
url = "http://search.com/search?term=%s&location=sf" % (str(q))

Use this it will be faster...