Reputation: 8585
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?
Upvotes: 0
Views: 4218
Reputation: 25
q = request.GET['q']
url = "http://search.com/search?term=%s&location=sf" % (str(q))
Use this it will be faster...
Upvotes: 2
Reputation: 380
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"
Upvotes: 2
Reputation: 5067
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)
Upvotes: 5