Nearby lessons
59 of 159Python - Escape Characters
- Understand what escape characters are and how they start with a backslash
- Use \n for a new line and \t for a horizontal tab
- Print double quotes inside strings using \"
- Explore the full list of escape characters including \r, \b, \f, \v, \' and \\
Introduction
Escape characters are special characters used inside string literals.
They start with a backslash (\) and give a special meaning to the next character.
Escape characters help us print special symbols, create new lines, insert tabs, and perform other formatting operations.
What are Escape Characters?
In Python, escape characters are used inside strings to perform special actions.
Each escape character begins with a backslash (\).
For example, \n creates a new line and \t inserts a horizontal tab.
Example 1 - New Line (\n)
Explanation
The \n escape character moves the cursor to the next line.
Everything after \n is printed on a new line.
Example 2 - Horizontal Tab (\t)
Explanation
The \t escape character inserts a horizontal tab space.
Example 3 - Using Double Quote Without Escape Character
Explanation
Python treats the second double quote as the end of the string.
Therefore, the remaining text becomes invalid and causes a SyntaxError.
Example 4 - Using Double Quote With Escape Character
Explanation
The \" escape character prints a double quote inside the string.
This allows us to include double quotes without ending the string.
Important Escape Characters
| Escape Character | Meaning |
|---|---|
\n |
New Line |
\t |
Horizontal Tab |
\r |
Carriage Return |
\b |
Back Space |
\f |
Form Feed |
\v |
Vertical Tab |
\' |
Single Quote |
\" |
Double Quote |
\\ |
Backslash Symbol |
- Escape characters start with a backslash and give special meaning to the next character
- \n moves the cursor to a new line and \t inserts a horizontal tab
- \" prints a double quote inside a string without ending it
- Unescaped double quotes inside a string cause a SyntaxError
- Common escapes include \r, \b, \f, \v, \' and \\