Python Special Characters
Essential guide to Python escape sequences, string types, and special characters. Learn \n, \t, Unicode, raw strings, f-strings, and avoid common gotchas.
Common Escape Sequences
Newline & Tab
\n creates a new line. \t inserts a tab character.
print("Hello\nWorld") # Two lines
print("Name:\tJohn") # Tab-separated
Quotes & Backslash
Escape quotes inside strings with \' or \". Use \\ for a literal backslash.
print('It\'s a string')
print("She said \"Hello\"")
print("C:\\Users\\path") # Windows path
Carriage Return & Others
\r returns cursor to line start. Less common: \b (backspace), \f (form feed), \v (vertical tab).
\n → Newline (line feed)
\t → Horizontal tab
\r → Carriage return
\\ → Literal backslash
\' → Single quote
\" → Double quote
String Types
Raw Strings
Prefix with r to treat backslashes as literal characters. Essential for regex and Windows paths.
path = r"C:\Users\name\file.txt"
regex = r"\d{3}-\d{4}" # Phone pattern
F-Strings (Python 3.6+)
Prefix with f for inline variable interpolation. Cleaner than .format() or % formatting.
name = "Alice"
age = 30
print(f"Name: {name}, Age: {age}")
print(f"Result: {10 + 5}") # Expressions work
Triple Quotes
Use """ or ''' for multiline strings. Preserves line breaks and indentation.
text = """
This is a multiline string.
It preserves line breaks.
Useful for docstrings.
"""
Unicode Strings
In Python 3, all strings are Unicode by default. Use \u or \U for Unicode escapes.
print("\u2764") # Heart emoji ❤
print("\U0001F600") # Grinning face 😀
print("Café") # Works directly in Python 3
Common Gotchas
Windows Paths: Use raw strings or forward slashes to avoid escape sequence issues.
# Wrong: \n is newline, \t is tab
path = "C:\new\test.txt"
# Correct options:
path = r"C:\new\test.txt" # Raw string
path = "C:/new/test.txt" # Forward slashes
path = "C:\\new\\test.txt" # Escaped backslashes
Mixing String Types: Can't end raw strings with a backslash. Combine prefixes carefully.
# This fails - raw string can't end with \
path = r"C:\folder\"
# Solutions:
path = r"C:\folder" + "\\"
path = "C:\\folder\\"
# F-strings work with raw strings
path = rf"C:\{folder}\file.txt"
Print vs Repr: print() interprets escapes, repr() shows them literally.
s = "Hello\nWorld"
print(s) # Hello
# World
print(repr(s)) # 'Hello\nWorld'
Best Practices
- Use raw strings (
r"") for regex patterns and file paths - Prefer f-strings for string formatting in Python 3.6+
- Use triple quotes for multiline strings and docstrings
- Be consistent with quote style — single or double quotes, pick one
- In Python 3, Unicode is default — no need for
u""prefix - Use
os.path.join()orpathlibfor cross-platform path handling