hellomello
hellomello

Reputation: 8585

django/python variables inside strings?

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

Answers (3)

Northlondoner
Northlondoner

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

Emil
Emil

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

craigmj
craigmj

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

Related Questions