W3docs

Python Escape Characters

Learn Python escape characters: newline, tab, unicode, hex, raw strings, and common gotchas with clear code examples.

This chapter covers Python escape characters — special two-character sequences that let you embed control characters, quotes, backslashes, and Unicode code points directly inside a string literal. You will learn every standard escape sequence, how raw strings switch them off, and the most common gotchas beginners run into.

What Is an Escape Character?

In Python string literals, the backslash (\) acts as an escape character. When the parser sees a backslash, it reads the next character (or characters) together and interprets the pair as a single special character — not as two ordinary characters.

msg = "Line one\nLine two"
print(msg)
# Line one
# Line two

Without \n, the string would be "Line one\nLine two" printed on one line; with it, the parser substitutes a real newline character (Unicode code point U+000A) before the string is stored.

The term escape comes from the idea that the backslash lets certain characters "escape" their normal meaning — for example, a quotation mark inside a same-quotation-mark string.

Reference Table of Escape Sequences

Python recognises the following escape sequences inside both single-quoted and double-quoted string literals (including triple-quoted strings):

SequenceNameUnicode / Hex
\nNewline (line feed)U+000A
\tHorizontal tabU+0009
\rCarriage returnU+000D
\bBackspaceU+0008
\fForm feedU+000C
\aBell (alert)U+0007
\vVertical tabU+000B
\0Null characterU+0000
\\Literal backslashU+005C
\'Literal single quoteU+0027
\"Literal double quoteU+0022
\oooCharacter by octal valuee.g. \101A
\xhhCharacter by hex valuee.g. \x41A
\uxxxxUnicode character (4 hex digits)e.g. éé
\UxxxxxxxxUnicode character (8 hex digits)e.g. \U0001F600 → 😀
\N{name}Unicode character by namee.g. \N{SNOWFLAKE} → ❄

Case matters. \n (newline) is completely different from \N{name} (named Unicode). \u and \U are also different. Always use the exact case shown above.

Everyday Escape Sequences

Newline (\n) and Tab (\t)

These are the two most commonly used escape sequences:

# \n inserts a line break
poem = "Roses are red,\nViolets are blue."
print(poem)
# Roses are red,
# Violets are blue.

# \t inserts a horizontal tab (usually 8 spaces wide in a terminal)
header = "Name\tAge\tCity"
row    = "Alice\t30\tBerlin"
print(header)
print(row)
# Name    Age     City
# Alice   30      Berlin

Embedding Quotes Inside Strings

You have two strategies: switch the outer quote style, or use an escape sequence.

# Strategy 1 — different outer quote
msg1 = 'She said "hello"'
msg2 = "it's fine"

# Strategy 2 — escape the quote
msg3 = "She said \"hello\""
msg4 = 'it\'s fine'

print(msg1)  # She said "hello"
print(msg4)  # it's fine

Both strategies produce identical strings. The escape approach is useful inside triple-quoted strings where switching quote style is awkward.

Backslash (\\)

Because the backslash is the escape character itself, you must double it to include a literal backslash:

python— editable, runs on the server

Carriage Return (\r) and Backspace (\b)

\r moves the cursor back to the beginning of the current line. Any characters printed after it overwrite what was already on the line. \b moves the cursor one position to the left.

# \r — carriage return
s = "ABCDE\rXY"
print(s)     # XYcde  (XY overwrites the first two characters)
print(repr(s))  # 'ABCDE\rXY'

# \b — backspace (moves cursor back one position)
s2 = "abc\bd"
print(repr(s2))  # 'abc\x08d'
# terminal may render as: abd  (b erased, d written in its place)

These sequences affect cursor position rather than inserting visible characters. Their visible result depends on your terminal emulator.

Numeric and Unicode Escapes

Hexadecimal (\xhh)

\x followed by exactly two hex digits inserts the character with that code point. This works in both byte strings and Unicode strings:

# \x41 = 65 decimal = 'A'
print("\x41\x42\x43")  # ABC

# Useful for non-printable control codes
nul = "\x00"
print(len(nul))    # 1
print(repr(nul))   # '\x00'

Octal (\ooo)

\ followed by one to three octal digits (0–7) inserts the character with that octal code point:

print("\101\102\103")  # ABC  (101 octal = 65 decimal = 'A')

Octal escapes are inherited from C and are rarely needed in modern Python. Prefer \x or \u for readability.

Unicode (\uxxxx and \Uxxxxxxxx)

\u takes exactly four hex digits; \U takes exactly eight. Both insert the corresponding Unicode character:

print("é")          # é  (Latin small letter e with acute)
print("π")          # π  (Greek small letter pi)
print("\U0001F600")      # 😀  (grinning face emoji)

Named Unicode (\N{name})

You can also reference a Unicode character by its official name. This is the most readable form for uncommon symbols:

print("\N{SNOWFLAKE}")                      # ❄
print("\N{LATIN SMALL LETTER E WITH ACUTE}") # é
print("\N{BLACK HEART SUIT}")               # ♥

The names are case-insensitive and come from the Unicode character database.

Raw Strings

A raw string is a string literal prefixed with r (or R). Inside a raw string, backslashes are treated as literal backslashes — no escape sequences are processed.

# Regular string — backslash starts an escape sequence
normal = "C:\new_folder\table.csv"
print(normal)
# C:
# ew_folder	able.csv   ← \n and \t were interpreted!

# Raw string — backslashes are literal
raw = r"C:\new_folder\table.csv"
print(raw)
# C:\new_folder\table.csv

Raw strings are essential when working with Windows file paths and regular expressions, where backslashes appear frequently:

import re

# Without raw string — need to double every backslash
pattern1 = re.compile("\\d+\\.\\d+")

# With raw string — much more readable
pattern2 = re.compile(r"\d+\.\d+")

print(pattern2.findall("pi is 3.14159"))  # ['3.14159']

Raw String Limitation

A raw string cannot end with an odd number of backslashes. The final backslash would still try to escape the closing quote:

# SyntaxError: EOL while scanning string literal
# path = r"C:\folder\"    ← the \" at the end escapes the quote

# Workaround — concatenate a regular string
path = r"C:\folder" + "\\"
print(path)  # C:\folder\

Common Gotchas

Unrecognised Escape Sequences

An escape sequence that is not in the standard table produces a warning or error depending on your Python version:

  • Python 3.6–3.11: DeprecationWarning (suppressed by default; visible with -W all)
  • Python 3.12+: SyntaxWarning (shown by default)
  • A future version will make it a SyntaxError
# \d is not a valid Python escape sequence
# python3 -W all script.py  => DeprecationWarning: invalid escape sequence '\d'
s = "\d+"
print(repr(s))     # '\\d+'  — backslash is kept literally for now

# Always use a raw string for regex patterns
import re
print(re.findall(r"\d+", "abc 123"))  # ['123']

Escape Sequences in Byte Strings

\u and \U and \N{name} are not valid inside byte literals (b"..."). Only \x, \ooo, \\, \', \", \n, \t, \r, \b, \f, \a, \v, and \0 work in byte strings:

b = b"\x41\x42"   # valid — b'AB'
print(b)

# b"é"       # SyntaxError — \u not allowed in bytes

Triple-Quoted Strings Still Honour Escapes

A triple-quoted string ("""...""" or '''...''') spans multiple lines and still processes escape sequences. Use a raw triple-quoted string if you need the backslashes literal:

sql = """
SELECT *
FROM users
WHERE name LIKE '%O\'Brien%'
"""
print(sql)

regex_pattern = r"""
(?x)            # verbose mode
\d{4}           # year
-\d{2}          # month
-\d{2}          # day
"""

Inspecting Strings with repr()

The built-in repr() function shows you the raw escape sequences inside a string, which is invaluable for debugging:

s = "line1\nline2\ttabbed"
print(s)         # prints with actual newline and tab
print(repr(s))   # 'line1\nline2\ttabbed'

Use repr() when a string "looks right" on screen but behaves unexpectedly — hidden characters like \r, \x00, or invisible Unicode spaces are immediately visible.

Practice

Practice
In Python, what are some possible uses of escape characters?
In Python, what are some possible uses of escape characters?
Was this page helpful?