Python String Escaping and Raw Strings
Learn Python string escaping including raw strings (r-strings), byte strings, f-string escaping, triple-quoted strings, and Unicode escape sequences. Covers Python 3 string handling best practices.
Detailed Explanation
Python String Escaping
Python provides a rich set of string types, each with different escaping behaviors. Understanding these options lets you choose the cleanest approach for any situation.
Standard Escape Sequences
Python recognizes these escape sequences in regular strings:
\\' → single quote
\\" → double quote
\\\\ → backslash
\\n → newline
\\r → carriage return
\\t → tab
\\b → backspace
\\f → form feed
\\a → bell/alert
\\0 → null character
\\ooo → octal character (up to 3 digits)
\\xhh → hex character (exactly 2 digits)
\\uxxxx → Unicode BMP (exactly 4 hex digits)
\\Uxxxxxxxx → Unicode full range (exactly 8 hex digits)
\\N{name} → Unicode character by name
Raw Strings
Prefixing a string with r disables escape sequence processing:
path = r"C:\Users\name\Documents" # backslashes are literal
regex = r"\d+\.\d+" # no double-escaping needed
Raw strings cannot end with an odd number of backslashes — r"path\" is a syntax error because the parser still uses backslash to escape the delimiter during tokenization.
Triple-Quoted Strings
Triple quotes (""" or ''') allow multiline content without \n:
sql = """
SELECT *
FROM users
WHERE name = 'O\'Brien'
"""
Escaping still works inside triple-quoted strings; they simply do not require escaping newlines.
F-String Escaping
In f-strings, curly braces are the interpolation delimiters. To include literal braces, double them:
f"{{not interpolated}}" # output: {not interpolated}
f"Value: {x}" # output: Value: 42
Backslash escapes work normally inside f-strings but cannot appear inside the {} expression.
Bytes vs. Strings
Python 3 distinguishes str (Unicode) from bytes. Byte strings (b"...") only accept ASCII characters and \xHH escapes — no \u or \N{}.
repr() for Debugging
repr() returns a string with all special characters escaped, making it invaluable for debugging:
>>> repr("line\n\ttab")
"'line\\n\\ttab'"
Use Case
Python string escaping is needed when writing file path handling code, building SQL queries with parameter binding, crafting regex patterns, processing text data in ETL pipelines, generating configuration files, writing test assertions involving special characters, and creating cross-platform scripts that handle Windows and Unix paths.