escape sequence
In Python, an escape sequence is a series of characters that represents a special character or action inside a string or bytes literal. They allow you to include characters in strings that are otherwise difficult or impossible to express directly, such as newlines, tabs, or quotes.
Escape sequences start with a backslash (\), followed by a character that has a special meaning. For instance, \n represents a newline, \t represents a tab, and \\ represents a literal backslash.
If the character after the backslash isn’t one of the recognized escapes, then Python leaves the backslash in the string unchanged. Since Python 3.12, this also emits a SyntaxWarning, and a future Python version will turn it into a SyntaxError.
For example, "\d" is an invalid escape sequence, so you should write it as "\\d" or use a raw string like r"\d" instead. In bytes literals, the string-only escapes \N{...}, \u, and \U count as unrecognized too.
Using escape sequences can make your strings more readable and easier to manage, especially when dealing with special characters or formatting requirements.
Example
Here’s a quick example of how to use escape sequences in Python:
>>> text = "Hello, Pythonistas!\nWelcome to Real Python!\tLet's learn Python!"
>>> print(text)
Hello, Pythonistas!
Welcome to Real Python! Let's learn Python!
When you run this code, you’ll see that \n creates a new line, and \t adds a tab space.
Related Resources
Tutorial
What Are Python Raw Strings?
In this tutorial, you'll learn the nuances of using raw string literals in your Python source code. Raw strings offer convenient syntax for including backslash characters in string literals without the complexity of escape sequences.
For additional information on related topics, take a look at the following resources:
- Strings and Character Data in Python (Tutorial)
- Unicode & Character Encodings in Python: A Painless Guide (Tutorial)
- Strings and Character Data in Python (Course)
- Python Raw Strings (Quiz)
- Python Strings and Character Data (Quiz)
- Unicode in Python: Working With Character Encodings (Course)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.
By Leodanis Pozo Ramos • Updated Sept. 21, 2026