Escape sequences in Python strings serve to represent special characters that either cannot be typed directly or carry specific formatting functions. These are denoted by a backslash (\) and instruct Python to interpret the following character differently from its literal meaning.
Common Escape Sequence Functions
\n — Line Feed
print('first line\nsecond line')
Output:
first line
second line
The \n sequence moves the subsequent text to a new line.
\t — Horizontal Tab
print('column1\tcolumn2')
This inserts a horizontal tab, typically aligning content every eight characters (though behavior may vary slightly across platforms).
\r — Carriage Return
print('old text\rcurrent text')
The \r moves the cursor to the beginning of the current line, allowing subsequent characters to overwrite existing ones. This results in:
current text
\b — Backspace
print('testing\bresult')
The \b removes the preceding character—in this case, the g from testing:
testinresult
\\ — Literal Backslash
print('path: C:\\folder')
Since the backslash itself is an escape character, two backslashes are needed to display one literal backslash.
\' — Single Quote in String
print("He said \'Hello!\'")
This allows inclusion of a single quote with in a string delimited by single quotes, preventing premature string termination.
Raw Strings: r'' or R''
print(r'no escape here:\n')
Output:
no escape here:\n
In raw strings, escape sequences like \n or \t are not interpreted and are printed literally.
Note: Raw strings must not end with a single backslash:
r'end\\' # ✅ Valid
r'end\' # ❌ Invalid
Summary of Escape Sequences
| Escape Sequence | Function |
|---|---|
\n |
New line |
\t |
Horizontal tab |
\r |
Carriage return |
\b |
Backspace |
\\ |
Literal backslash |
\', \" |
Quote characters |
r'...' |
Raw string (no escape processing) |