字符串中的 django/python 变量?

hel*_*llo 0 python django variables dynamic

我是 python 新手,需要一些帮助。

我有一个变量

q = request.GET['q']
Run Code Online (Sandbox Code Playgroud)

如何在其中插入变量q

url = "http://search.com/search?term="+q+"&location=sf"
Run Code Online (Sandbox Code Playgroud)

现在我不确定公约是什么?我习惯了 PHP 或 javascript,但我正在学习 python,如何动态插入变量?

cra*_*gmj 5

使用String的格式化方法:

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

但当然你应该对 q 进行 URL 编码:

import urllib
...
qencoded = urllib.quote_plus(q)
url = 
  "http://search.com/search?term={0}&location=sf".format(qencoded)
Run Code Online (Sandbox Code Playgroud)