How to add quotes to a string in Python

avatar

Borislav Hadzhiev

Mon Jun 20 20222 min read

banner

Photo by Axel Holen

Add quotes to a string in Python #

To add quotes to a string in Python:

  1. Alternate between single and double quotes.
  2. For example, to add double quotes to a string, wrap the string in single quotes.
  3. To add single quotes to a string, wrap the string in double quotes.
main.py
# 👇️ alternating single and double quotes result_1 = '"apple"' # 👇️ using a formatted string literal my_str = 'apple' result_2 = f'"{my_str}"' # 👇️ escaping double quotes with a backslash result_3 = "\"apple\""

The first example in the code snippet alternates between single and double quotes.

main.py
result_1 = '"apple"'

If a string is wrapped in single quotes, we can use double 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 single quotes to a string, wrap the string in double quotes.

main.py
result_1 = "one 'two' three"

In some rare cases your string might contain both single and double quotes. To get around this, use a triple-quoted string.

main.py
result_1 = """ "one" two 'three' """

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
main.py
example = ''' It's Alice "hello" ''' # # It's Alice # "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.

An alternative is to use a formatted string literal.

main.py
my_str = 'one' result_2 = f'"{my_str}" "two"' print(result_2) # 👉️ '"one" "two"'

Notice that we still have to alternate between single and double quotes.

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

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

Make sure to wrap expressions in curly braces - {expression}.

You can also use a backslash \ to escape quotes.

main.py
result_3 = "\"one\" \"two\"" print(result_3) # 👉️ '"one" "two"'

In most cases, it is preferable (and more readable) to alternate between single and double quotes, but escaping quotes can also be useful (e.g. in rare cases in a JSON string).

Use the search field on my Home Page to filter through my more than 1,000 articles.