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?

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

I've also seen sometimes using %? Why the difference? Thanks!
You could use the % approach, but it's the 'old' approach : url = "http://...?term=%s&location=s" % (qencoded,) For a full discussion see stackoverflow.com/questions/5082452/…
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"

Comments

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

Use this it will be faster...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.