9.3 Escape Characters
The full table of Python string escape sequences, including the less common octal and hex character codes, expanding on the introductory table in Chapter 4.
The core escape sequences (\n, \t, \\, quotes) were introduced in 4.13 Escape Characters. This is the complete reference, including the octal and hex forms.
| Escape | Meaning | Example |
|---|---|---|
\n | Newline | "a\nb" → two lines |
\t | Tab | "a\tb" → "a b" |
\\ | Literal backslash | "a\\b" → a\b |
\' | Literal single quote | 'it\'s' → it's |
\" | Literal double quote | "say \"hi\"" → say "hi" |
\r | Carriage return | used in some line-ending formats |
\b | Backspace | moves cursor back one position |
\f | Form feed | page-break control character |
\ooo | Character by octal code | \101 → 'A' |
\xhh | Character by hex code | \x41 → 'A' |
>>> print("\101\102\103") # octal escapes
ABC
>>> print("\x41\x42\x43") # hex escapes
ABC
Quick Interview Answer
“Beyond the everyday
\n,\t, and quote escapes, Python also supports character-by-code escapes:\ooofor octal and\xhhfor hex. Both resolve to a single character at parse time —\x41and\101are two different ways of writing the letter'A'. These are rarely needed for hand-written code but show up when strings are generated programmatically from raw byte or code-point values.”
Common Mistakes
- Confusing
\x41(a single hex-escaped character) with a literal two-character sequence — it always collapses to one character in the resulting string. - Writing an octal escape with a digit
\8or\9and expecting it to work — octal digits only go up to7, so those aren’t valid octal escapes. - Reaching for raw strings (
r"...") when the octal/hex escapes are actually needed — a raw string disables all escape processing, including these.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form