the full guide

Escape characters and raw strings

An escape character is a backslash followed by a letter, which stands for a special character such as a new line (\n) or a tab (\t). A raw string, written r"...", treats backslashes as ordinary characters.

5 min Intermediate

What you need: The earlier topics of this module.

Definition

An escape character is a backslash followed by a letter, which stands for a special character such as a new line (\n) or a tab (\t). A raw string, written r"...", treats backslashes as ordinary characters.

In simple words

You can't press Enter inside a normal string, so \n means "new line here". If you want a real backslash, as in a Windows path, you either double it or put r in front.

Why it matters

Windows file paths and regular expressions are full of backslashes. Forgetting this is a very common source of confusing errors.

How it works

CodeMeans
\nNew line
\tTab
\\A backslash
\"A double quote
\'A single quote
\u0905A Unicode character (अ)

In code

escape.py
print("Line one\nLine two")
print("Name:\tRiya")
print("She said \"hello\"")
print("C:\\new\\table")
print(r"C:\new\table")
print(len("\n"), len(r"\n"))

Output

Line one
Line two
Name:	Riya
She said "hello"
C:\new\table
C:\new\table
1 2

Common mistakes

  • Writing "C:\new\table". \n and \t become a new line and a tab. Use a raw string or forward slashes.
  • Ending a raw string with a single backslash: r"C:\" is an error.

Check yourself

Question 1

1. What does \t produce?

Question 2

2. How long is the string r"\n"?

Summary

  • A backslash starts an escape code.
  • Raw strings keep backslashes as they are, which suits paths and regex.

Finished reading?

Sources: The Python Tutorial, python.org