adohertyd
adohertyd

Reputation: 2689

Enclose a variable in single quotes in 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

Upvotes: 23

Views: 90350

Answers (6)

Jab
Jab

Reputation: 27485

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!

Upvotes: 6

Hugh Bothwell
Hugh Bothwell

Reputation: 56624

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}'")
    

Upvotes: 42

glaed
glaed

Reputation: 441

I just stumbled upon some code doing it this way:

term = urllib.quote(term.join(("'", "'")))

(In this case join() uses term as a separator to combine all elements that were given in the iterable parameter into one string. Since there are only two elements, they are simply wrapped around one instance of term.)

Although it is quite readable, I would still consider it a hack and less readable than other options. Therefore, I recommend the use of string formatting as mentioned by others:

term = urllib.quote("'{}'".format(term))

Upvotes: 0

sean
sean

Reputation: 3985

What's wrong with adding the single quotes after it being url encoded? Or, just adding them before hand in you encode function above?

Upvotes: 2

Amber
Amber

Reputation: 526513

You can just use string interpolation:

>>> term = "foo"
>>> "'%s'" % term
"'foo'"

Upvotes: 11

Jakob Bowyer
Jakob Bowyer

Reputation: 34688

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

Should be what you are looking for.

Upvotes: 3

Related Questions