Python Tutorial
Python Escape Characters
An escape character is a backslash followed by a character you want to insert, such as a quote inside a string.
Escape Quotes
Insert a quote inside a string that uses the same quote character.
txt = "We are the so-called \"Vikings\" from the north."
print(txt)Common Escapes
\\ is a backslash, \n is a new line, \t is a tab, \r is a carriage return.
print("Line1\nLine2")
print("Col1\tCol2")
print("C:\\Users\\Luna")📘 Real-World Deep Dive
Python's escape-character story is bigger than the <code>\n</code> many beginners remember. Raw strings (<code>r"…"</code>), escape vs. literal in regex, and double-escape in code-then-data layers are daily bugs if misunderstood.
Real-Life Scenario
A small utility that turns a user-supplied regex into something safe to embed in a generated Python source file.
Real-Life Example
import re
PASSWORD_RX = re.compile(r"^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{8,}$")
def to_python_source(rx: re.Pattern, name: str = "RX") -> str:
body = rx.pattern
# Escape every backslash so the resulting Python source still
# produces the same regex after compilation.
escaped = body.replace("\\", "\\\\").replace('"', '\\"')
return f"{name} = re.compile(r"{escaped}")"
print(to_python_source(PASSWORD_RX))
tests = ["abcdEf1!", "short1A", "alllower1", "BIGUPPER1", "Abcdefg0"]
for t in tests:
print(f"{t!r:<10} -> {bool(PASSWORD_RX.fullmatch(t))}")Expected Output
RX = re.compile(r"^(?=.*[A-Z])(?=.*[a-z])(?=.*d).{8,}$")
'abcdEf1!' -> True
'short1A' -> False
'alllower1' -> False
'BIGUPPER1' -> False
'Abcdefg0' -> TrueCommon mistakes
- Mixing raw strings with f-strings is a syntax error:
fr"…"doesn't exist — userf"…"since 3.12. - Embedding a regex pattern inside a regex pattern literally is a recipe for extra commas and missing quotes.
ord("\n") == 10andchr(10)are useful for treacing escaped sequences.
🚀 Performance & Best Practices
- Use
re.escapeto make user strings regex-safe — never double-escape by hand. - Raw strings (
r"…") avoid 4× escape amplification on Windows paths. - For triple-escaped Windows paths, prefer
pathlib.Path(...).as_posix().
🧪 Try It Yourself
- Write a
to_sourcefunction that round-trips throughast.parseand recompiles. - Add support for pattern flags (
re.IGNORECASE) in the embedded source. - Build a small CLI that takes a regex and emits an equivalent Python file.