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
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}'")
You can just use string interpolation:
>>> term = "foo"
>>> "'%s'" % term
"'foo'"
For those that are coming here while googling something like "python surround string" and are time conscientious (or just looking for the "best" solution).
I was going to add in that there are now f-strings which for Python 3.6+ environments are way easier to use and (from what I read) they say are faster.
#f-string approach
term = urllib.parse.quote(f"'{term}'")
I decided to do a timeit of each method of "surrounding" a string in python.
import timeit
results = {}
results["concat"] = timeit.timeit("\"'\" + 'test' + \"'\"")
results["%s"] = timeit.timeit("\"'%s'\" % ('test',)")
results["format"] = timeit.timeit("\"'{}'\".format('test')")
results["f-string"] = timeit.timeit("f\"'{'test'}'\"") #must me using python 3.6+
results["join"] = timeit.timeit("'test'.join((\"'\", \"'\"))")
for n, t in sorted(results.items(), key = lambda nt: nt[1]):
print(f"{n}, {t}")
Results:
concat, 0.009532792959362268
f-string, 0.08994143106974661
join, 0.11005984898656607
%s, 0.15808712202124298
format, 0.2698059631511569
Oddly enough, I'm getting that concatenation is faster than f-string every time I run it, but you can copy and paste to see if your string/use works differently, there may also be a better way to put them into timeit than \
escaping all the quotes so let me know
Try it online!
def wrap_and_encode(x):
return encode("'%s'" % x)
Should be what you are looking for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With