Add double quotes around a variable in Python

avatar

Borislav Hadzhiev

Last updated: Jun 20, 2022

banner

Photo from Unsplash

Add double quotes around a variable in Python #

Use a formatted string literal to add double 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.

main.py
my_str = 'hello world' result = f'"{my_str}"' print(result) # 👉️ "hello world"

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 the variable in curly braces - {my_var}.

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

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

main.py
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 double quotes in the variable declaration, but make sure to wrap the variable in single or triple quotes.

main.py
my_str = '"hello world"' print(my_str) # "hello world"

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 double quotes in a string that was wrapped in double 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.

main.py
result_1 = """ "one 'two' three" """ # 👇️ "one 'two' three" print(result_1)

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 Bob "hello" ''' # # It's Bob # "hello" # print(example)

The string in the example 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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.