在Python中用单引号括起变量

ado*_*tyd 16 python

如何在python中的单引号中包含变量?它可能很简单,但我似乎无法得到它!我需要对变量进行url编码term.Term由用户以表单形式输入,并传递给url编码的函数term=urllib.quote(term).如果用户输入"apple computer"作为他们的术语,则在url-encoding之后它将是"apple%20comptuer".我想要做的是在url编码之前使用单引号括起来的术语,以便在url-encoding"%23apple%20computer%23"之后它将是"'apple computer'".我需要将该术语传递给URL,除非我使用这种语法,否则它将无效.有什么建议?

示例代码:

import urllib2
import requests    

def encode():
        import urllib2
        query= avariable #The word this variable= is to be enclosed by single quotes
        query = urllib2.quote(query)
        return dict(query=query)

def results():

    bing = "https://api.datamarket.azure.com/Data.ashx/Bing/SearchWeb/Web?Query=%(query)s&$top=50&$format=json"
    API_KEY = 'akey'

    r = requests.get(bing % encode(), auth=('', API_KEY))
    return r.json
Run Code Online (Sandbox Code Playgroud)

Hug*_*ell 31

有三种方式:

  1. 字符串连接

    term = urllib.quote("'" + term + "'")
    
    Run Code Online (Sandbox Code Playgroud)
  2. 旧式字符串格式

    term = urllib.quote("'%s'" % (term,))
    
    Run Code Online (Sandbox Code Playgroud)
  3. 新式字符串格式

    term = urllib.quote("'{}'".format(term))
    
    Run Code Online (Sandbox Code Playgroud)


Amb*_*ber 9

你可以使用字符串插值:

>>> term = "foo"
>>> "'%s'" % term
"'foo'"
Run Code Online (Sandbox Code Playgroud)


Jab*_*Jab 6

对于那些在谷歌搜索“python Surround String”之类的内容时来到这里并且注重时间的人(或者只是寻找“最佳”解决方案)

\n

我要补充的是,现在有f 字符串,对于 Python 3.6+ 环境来说更容易使用,而且(根据我读到的)他们说速度更快。

\n
#f-string approach\nterm = urllib.parse.quote(f"\'{term}\'")\n
Run Code Online (Sandbox Code Playgroud)\n

我决定做一次我决定对python 中“包围”字符串的每种方法

\n
import timeit\n\nresults = {}\n\nresults["concat"] = timeit.timeit("\\"\'\\" + \'test\' + \\"\'\\"")\nresults["%s"] = timeit.timeit("\\"\'%s\'\\" % (\'test\',)")\nresults["format"] = timeit.timeit("\\"\'{}\'\\".format(\'test\')")\nresults["f-string"] = timeit.timeit("f\\"\'{\'test\'}\'\\"") #must me using python 3.6+\nresults["join"] = timeit.timeit("\'test\'.join((\\"\'\\", \\"\'\\"))")\n\nfor n, t in sorted(results.items(), key = lambda nt: nt[1]):\n    print(f"{n}, {t}")\n
Run Code Online (Sandbox Code Playgroud)\n

结果:

\n
concat, 0.009532792959362268\nf-string, 0.08994143106974661\njoin, 0.11005984898656607\n%s, 0.15808712202124298\nformat, 0.2698059631511569\n
Run Code Online (Sandbox Code Playgroud)\n

奇怪的是,我每次运行它时都发现连接比 f-string 更快,但是您可以复制并粘贴以查看您的字符串/使用是否工作不同,也可能有更好的方法将它们放入 timeit比\\逃避所有的引号,所以让我知道

\n

在线尝试一下!

\n