Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enclose a variable in single quotes in Python

Tags:

python

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
like image 839
adohertyd Avatar asked Jul 05 '12 19:07

adohertyd


4 Answers

There are four ways:

  1. string concatenation

    term = urllib.quote("'" + term + "'")
    
  2. old-style string formatting

    term = urllib.quote("'%s'" % (term,))
    
  3. new-style string formatting

    term = urllib.quote("'{}'".format(term))
    
  4. f-string style formatting (python 3.6+)

    term = urllib.quote(f"'{term}'")
    
like image 114
Hugh Bothwell Avatar answered Oct 19 '22 05:10

Hugh Bothwell


You can just use string interpolation:

>>> term = "foo"
>>> "'%s'" % term
"'foo'"
like image 28
Amber Avatar answered Oct 19 '22 07:10

Amber


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!

like image 5
Jab Avatar answered Oct 19 '22 07:10

Jab


def wrap_and_encode(x):
    return encode("'%s'" % x)

Should be what you are looking for.

like image 3
Jakob Bowyer Avatar answered Oct 19 '22 06:10

Jakob Bowyer