How to put single quotes around variable in 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!

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.'

print(example1)
print(example2)

Output:

He said 'See ya' and closed the door.
They said "We will miss you" as he left.

Python Strings

Python strings are sequences of characters and numbers.

A string is wrapped around a set of single quotes or double quotes. There is no difference in which you use.

Anything that goes inside the quotes is interpreted as being “text” instead an executable command.

To demonstrate, here are some examples.

print("10 + 20")                  # Prints: 10 + 20
print("This # is not a comment")  # Prints: This # is not a comment
print("pow(2,3)")                 # Prints: pow(2, 3)

In each example, there is a Python operation that would normally execute. But because the expression is wrapped inside a string, the expression is printed out as-is.

But here is where it gets interesting. Let’s see what happens when you place a double quote inside a string:

print("This "test" causes problems")

Result:

  File "example.py", line 1
    print("This "test" causes problems")
                 ^
SyntaxError: invalid syntax

This happens because the Python interpreter sees a string of the expression in three parts:

  1. "This "
  2. test
  3. " causes problems"

It sees two strings and a reference to a non-existent object test. Thus it has no idea what to do.

To come over this issue, you have two options:

  1. Use single quotes inside double quotes (and vice versa).
  2. Escape the quotes inside a string with a backslash.

1. Single Quotes inside Double Quotes

To write a quoted string inside another string in Python

  • Use double quotes in the outer string, and single quotes in the inner string
  • Use single quotes in the outer string and double quotes in the inner string

Here is an example:

example1 = "He said 'See ya' and closed the door."
example2 = 'They said "We will miss you" as he left.'

print(example1)
print(example2)

Output:

He said 'See ya' and closed the door.
They said "We will miss you" as he left.

But what if this is not enough? What if you want to have quotes inside quotes?

Then you need to resort to what is called escape sequences. These make it possible to add as many quotes in a string as you want.

2. How to Escape Quotes in a String

To add quoted strings inside of strings, you need to escape the quotation marks. This happens by placing a backslash (\) before the escaped character.

In this case, place it in front of any quotation mark you want to escape.

Here is an example.

example1 = "This is a \"double quote\" inside of a double quote"
example2 = 'This is a \'single quote\' inside of a single quote'

print(example1)
print(example2)

Output:

This is a "double quote" inside of a double quote
This is a 'single quote' inside of a single quote

How to Use a Backslash in a String Then

In Python, the backslash is a special character that makes escaping strings possible.

But this also means you cannot use it normally in a string.

For example:

print("This\is\a\test")

Output:

This\is est

To include a backslash in a string, escape it with another backslash. This means writing a double backslash (\\).

For example:

print("This\\is\\a\\test")

Output:

This\is\a\test

Conclusion

Today you learned how to quote a string in Python.

Thanks for reading. I hope you enjoy it!

Happy coding!

Further Reading

Python Double Quote vs Single Quote

Useful Advanced Features of Python

How do I display single quotes in Python?

' You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string.

How do you pass variables in single quotes?

`echo` command prints the value of this variable without any quotation. When the variable is quoted by single quote then the variable name will print as output. If the backslash ( \ ) is used before the single quote then the value of the variable will be printed with single quote.

How do you put a variable in a quote?

When referencing a variable, it is generally advisable to enclose its name in double quotes. This prevents reinterpretation of all special characters within the quoted string -- except $, ` (backquote), and \ (escape).

Does Python accept single quotes?

There are two ways to represent strings in python. String is enclosed either with single quotes or double quotes. Both the ways (single or double quotes) are correct depending upon the requirement.