Enclose a variable in single quotes in Python
python
Solution
There are four ways:
string concatenation
term = urllib.quote("'" + term + "'")
old-style string formatting
term = urllib.quote("'%s'" % (term,))
new-style string formatting
term = urllib.quote("'{}'".format(term))
f-string style formatting (python 3.6+)
term = urllib.quote(f"'{term}'")
Problem
How do I enclose a variable within single quotations in python? It's probably very simple but I can't seem to get it! I need to url-encode the variable `term`. `Term` is entered in a form by a user and is passed to a function where it is url-encoded `term=urllib.quote(term)`. If the user entered "apple computer" as their term, after url-encoding it would be "apple%20comptuer". What I want to do is have the term surrounded by single-quotes before url encoding, so that it will be "'apple computer'" then after url-encoding "%23apple%20computer%23". I need to pass the term to a url and it won't work unless I use this syntax. Any suggestions? Sample Code: ``` 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 ```