Add backslashes to a string without escaping in Python

avatar

Borislav Hadzhiev

Last updated: Sep 4, 2022

banner

Photo from Unsplash

Add backslashes to a string without escaping in Python #

Use a raw string to add backslashes to a string without escaping, e.g. r'yes\no\maybe'. When a string is prefixed with r, it treats backslashes as literal characters and escaping them is not necessary.

main.py
# ✅ add backslashes to string without escaping them my_str = r'yes\no\maybe' print(my_str) # 👉️ yes\no\maybe # --------------------------------------- # ✅ add backslashes to string (str.replace()) my_str = 'yes_no_maybe' result = my_str.replace('_', r'\_') print(result) # 👉️ yes\_no\_maybe # --------------------------------------- # ✅ using variables in a raw, formatted string literal variable = 'maybe' my_str = fr'yes\no\{variable}' print(my_str) # 👉️ yes\no\maybe

The first example uses a raw string to add literal backslash characters to the string without escaping them.

Strings that are prefixed with r are called raw strings and treat backslashes as literal characters.

If you need to add a backslash character before a specific character in the string, use the str.replace() method.

main.py
my_str = 'yes_no_maybe' result = my_str.replace('_', r'\_') print(result) # 👉️ yes\_no\_maybe

The str.replace method returns a copy of the string with all occurrences of a substring replaced by the provided replacement.

The method takes the following parameters:

NameDescription
oldThe substring we want to replace in the string
newThe replacement for each occurrence of old
countOnly the first count occurrences are replaced (optional)

The method doesn't change the original string. Strings are immutable in Python.

If you need to use variables in a raw string, use a formatted string literal.

main.py
variable = 'maybe' my_str = fr'yes\no\{variable}' print(my_str) # 👉️ yes\no\maybe
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

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

Notice that we prefixed the string with fr and not just with f.

If you need to define a multiline string in which you don't have to escape special characters, use a triple-quoted raw string.

main.py
my_str = r"""yes \no \maybe""" # yes # \no # \maybe print(my_str)

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

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.