Enclose string in single quotes python

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!

Add single quotes around a variable in Python #

Use a formatted string literal to add single quotes around a variable in Python, e.g. result = f"'{my_var}'". Formatted string literals let us include variables inside of a string by prefixing the string with f.

Copied!

my_str = "hello" result = f"'{my_str}'" print(result) # 👉️ 'hello'

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

Copied!

my_str = 'is subscribed:' my_bool = True result = f"{my_str} '{my_bool}'" print(result) # 👉️ is subscribed: 'True'

Make sure to wrap the variable in curly braces - {my_var}.

Notice that we wrapped the f-string in double quotes to be able to use single quotes inside of the string.

You can also use the str.format() method to add single quotes around a string.

Copied!

my_bool = True result = "is subscribed: '{}'".format(my_bool) print(result) # 👉️ is subscribed: 'True'

The str.format method performs string formatting operations.

The string the method is called on can contain replacement fields specified using curly braces {}.

You can also include the single quotes in the variable declaration, but make sure to wrap the variable in double or triple quotes.

Copied!

my_str = "'hello'" print(my_str) # 👉️ 'hello'

If a string is wrapped in double quotes, we can use single quotes in the string without any issues.

However, if we try to use single quotes in a string that was wrapped in single quotes, we end up terminating the string prematurely.

If you need to add both single and double quotes in a string, use a triple-quoted string.

Copied!

my_str = """ "hello" 'world' """ print(my_str) # 👉️ "hello" 'world'

Triple-quotes strings are very similar to basic strings that we declare using single or double quotes.

But they also enable us to:

  • use single and double quotes in the same string without escaping
  • define a multi-line string without adding newline characters

Copied!

example = ''' It's Bob "hello" ''' # # It's Bob # "hello" # print(example)

The string in the example above uses both single and double quotes and doesn't have to escape anything.

End of lines are automatically included in triple-quoted strings, so we don't have to add a newline character at the end.

How do you enclose a string in a single quote Python?

In a string enclosed in single quotes ' , double quotes " can be used as is, but single quotes ' must be escaped with a backslash and written as \' .

How do you wrap a string in a quote in Python?

To quote a string in Python use single quotation marks inside of double quotation marks or vice versa. For instance: example1 = "He said 'See ya' and closed the door." example2 = 'They said "We will miss you" as he left.

How do you enclose a value in a quote in Python?

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

How do you add single quotes to text in Python?

How to put quotes in a string in Python.
double_quotes = '"abc"' String with double quotes. print(double_quotes) ... .
single_quotes= "'abc'" String with single quotes. print(single_quotes) ... .
both_quotes= """a'b"c""" String with both double and single quotes. print(both_quotes) ... .
double_quotes = "\"abc\"" Escape double quotes..