Prevent escape sequence interpretation in Python


Borislav Hadzhiev

Last updated: Sep 4, 2022


Photo from Unsplash

Prevent escape sequence interpretation in Python #

Use a raw string to prevent escape sequence interpretation, e.g. my_str = r'one\two\three'. When a string is prefixed with r, it treats backslashes as literal characters and escaping them is not necessary.
# ✅ Prevent escape sequence interpretation (raw string) my_str = r'one\two\three' print(my_str) # 👉️ one\two\three # ------------------------------------------- # ✅ Prevent escape sequence interpretation in file path (forward slashes) file_name = 'C:/Users/Carl/Desktop/avatar.png' # 👇️ C:/Users/Jim/Desktop/nature.jpg print(file_name)

The first example uses a raw string to prevent escape sequence interpretation.
my_str = r'one\two\three' print(my_str) # 👉️ one\two\three # 👇️ if you don't use a raw string print('one\two\three') # 👉️ one wo hree

Raw strings prevent automatic escaping of special characters.

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

If you need to use variables in the string, use a formatted string literal.
variable = 'two' my_str = fr'one\{variable}\three' print(my_str) # 👉️ one\two\three

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 are constructing a path, e.g. to a directory or a file, you can use forward slashes instead of backslashes.
file_name = 'C:/Users/Carl/Desktop/avatar.png' # 👇️ C:/Users/Jim/Desktop/nature.jpg print(file_name)

A forward slash can be used in the place of a backslash when you need to specify a path.

If you need to prevent escape sequence interpretation in a multiline string, use a triple-quoted string.
my_str = r"""one \two \three""" print(my_str)

Triple-quoted strings enable us to:

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

Another common way to escape a backslash character is to use a second backslash.
my_str = 'one\\two\\three' print(my_str) # 👉️ one\two\three

The first backslash is the escape character and the second is the literal character.

Backslash characters have a special meaning in Python, so to treat them as literal characters, we have to:

  • prefix the string with r to mark it as a raw string
  • use forward slashes in the place of backslashes in a path
  • escape each backslash with a second backslash
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.