Escape Characters
Python · Strings
Theory
Some characters cannot be typed directly inside a string literal, so Python uses escape sequences that start with a backslash. \n is a newline, \t is a tab, \ is one literal backslash, and \' or \" puts a quote inside a string that uses the same quote. Each escape sequence becomes a single character in memory: len('\n') is 1. print('Line1\nLine2') shows two lines.
Prefixing a literal with r creates a raw string, in which backslashes are kept as ordinary characters: len(r'\n') is 2. Raw strings are the standard way to write Windows paths like r'C:\new' (without the r, \n would become a newline) and regular expressions, which use many backslashes. Another way to avoid escaping quotes is simply to choose the other quote type: "It's" needs no escape. When you print the repr() of a string, Python shows the escapes back to you, which helps find hidden newlines or tabs in data.
Why we use it
Text often needs line breaks, tabs, quotes and backslashes. Escape sequences let you put them in a literal, and knowing them helps you debug data with invisible characters like stray \r\n line endings.
When to use it
Use \n and \t when building multi-line or tab-separated output. Use raw strings for Windows paths and regex patterns. Use repr() to reveal hidden escape characters when cleaning data.
How it works
- Python reads a string literal
- Is it a raw string (r prefix)? Yes: Keep every backslash as a normal character. No: Look for backslash sequences.
- Found a known escape like \n or \t? Yes: Replace the pair with one special character. No: Keep the characters as typed.
- Store the final characters as the string object
- print() shows the real newline or tab
Syntax
\n \t \' \" \Example
print('Line1\nLine2\tTabbed')Key points
- \n is newline, \t is tab, \ is a literal backslash
- Each escape sequence counts as one character in len()
- Prefix with r (raw string) to disable escaping entirely
- Use the other quote type to avoid escaping: "It's"
- repr() reveals hidden escapes like \n or \t in data