Escape Characters
2 min read ·
Escape characters in Python are used to insert special characters into strings that are otherwise difficult or impossible to write directly.
They start with a backslash (
\) followed by a character.What Are Escape Characters?
Escape characters allow you to:
- Add new lines
- Insert tabs
- Include quotes inside strings
- Represent special characters
Definition
An escape character is a backslash followed by a character that has a special meaning in a string.
New Line (\n)
The
\n escape character creates a new line in the output.Tab (\t)
The
\t escape character inserts a tab space.Backslash (\\)
To print a backslash, you must escape it using another backslash.
Single Quote (\')
Used to include a single quote inside a single-quoted string.
Double Quote (\")
Used to include double quotes inside a double-quoted string.
Carriage Return (\r)
The
\r escape character moves the cursor to the start of the line.Backspace (\b)
The
\b escape character removes the character before it.Form Feed (\f)
Used to insert a form feed (rarely used).
Raw Strings (r)
Raw strings ignore escape characters and treat them as normal text.
Best Practice
Use raw strings when working with file paths and regular expressions.
Exercise
- Print text on multiple lines using
\n - Print a Windows file path
- Use raw string to avoid escape characters