Escape Characters
Common Escape Sequences
Escape sequences allow you to include special characters inside strings that would otherwise be hard to represent. The most common ones are shown below.
Escape | Description | Example |
---|---|---|
\n | New line | print("Line1\nLine2") # Line1 then Line2 on next line |
\t | Tab | print("Name:\tAlice") # Adds a horizontal tab |
\\ | Backslash | print("C:\\path") # Prints C:\path |
\" | Double quote | print("He said \"Hi\"") # He said "Hi" |
\' | Single quote | print('Don\'t') # Don't |
\r | Carriage return | print("Overwrite\rNew") # 'Newwrite' |
\b | Backspace | print("Hel\blo") # 'Hlo' |
Raw Strings
Prefixing a string with 'r' (or 'R') creates a raw string, where backslashes are treated as literal characters instead of escape sequences. This is especially useful for file paths and regular expressions.
Example
# Regular vs raw strings
print("C:\\Users\\Alice") # C:\Users\Alice
print(r"C:\Users\Alice") # C:\Users\Alice
# Useful for regex patterns
import re
pattern = r"\d+" # Matches one or more digits
Output
C:\Users\Alice C:\Users\Alice
Unicode Escapes
Python strings are Unicode by default. Escape sequences can represent Unicode characters by name or by code point. Byte strings use hexadecimal escape sequences for binary data.
Example
# Unicode characters
print("\u03A9") # Greek Omega: Ω
print("\N{SNOWMAN}") # Unicode by name: ☃
print("\U0001F600") # Full code point: 😀
# Byte strings
byte_str = b"\x48\x65\x6C\x6C\x6F" # Represents b'Hello'
print(byte_str)
Output
Ω ☃ 😀 b'Hello'