037. Escape Characters
Embed special characters in string literals
037. Escape Characters
RAM Manager: Generating Report Text
Aryan’s RAM manager needs to generate multi-line reports, tab-separated columns, and handle Windows paths (for when his tool runs cross-platform).
The classic Python gotcha: Windows paths.
# This silently corrupts the path!
path = "C:\Users\alice\notes.txt"
# \U → Unicode escape, \a → bell char, \n → newline
# Python might raise SyntaxWarning or produce garbage
# Correct ways:
path = "C:\\Users\\alice\\notes.txt" # double backslash
path = r"C:\Users\alice\notes.txt" # raw stringAryan’s make_path() has this exact bug. His make_tabbed is missing the tab character. His make_quoted doesn’t wrap the text in double quotes.
💡 Fun fact: The backslash escape convention dates back to the C language (1972) and was adopted by nearly every language since. The specific sequences \n (newline) and \t (tab) come from ASCII control codes designed in the 1960s for teletype machines — \n literally moved the paper to the next line, and \t advanced to the next tab stop on the print head.
⚠️ Watch out: The Windows path bug is one of the most common cross-platform mistakes. "C:\new_folder" silently becomes "C:\n" + "ew_folder" because \n is a newline — no error, just garbage data. Always use raw strings r"C:\new_folder" or forward slashes "C:/new_folder" (Windows accepts both) for file paths.
🤔 Think about it: Raw strings r"\n" contain a literal backslash and the letter n — two characters. Regular "\n" contains a single newline character. If you print(r"\n") vs print("\n"), you get different output. How would this difference matter when writing regular expressions, where patterns like \d mean “digit”?
Learning objectives
- Use \n and \t for newline and tab
- Escape backslashes with \ in regular strings
- Use raw strings r“…“ to avoid escape confusion
Key concepts
- escape characters
- \n
- \t
- raw strings
Try it
Concept detail
Escape sequences let you embed special characters in string literals: \n newline (moves to next line) \t horizontal tab \ literal backslash ' single quote (in single-quoted strings) " double quote (in double-quoted strings) \r carriage return (used in Windows line endings \r\n) \0 null byte \uXXXX Unicode character by code point (e.g., \u00e9 = é) \xHH hex byte value
Raw strings r“…“ treat every backslash literally — no escape processing: r“C:\Users\alice“ == “C:\Users\alice” r“\n“ is two characters: backslash and n, NOT a newline
Use raw strings for:
- Windows paths: r“C:\Users\alice“
- Regular expressions: r“\d+.\d+“ (otherwise you’d write “\d+\.\d+”)
Triple-quoted strings “”“…”“” can contain literal newlines without \n: msg = “”“Line 1 Line 2”“”
Solution
def make_multiline(lines):
return "\n".join(lines)
def make_tabbed(label, value):
return label + ":\t" + value
def make_path():
return "C:\\Users\\alice\\notes.txt"
def make_quoted(text):
return 'He said: "' + text + '"'Tests
def test_multiline():
result = make_multiline(["line1", "line2", "line3"])
assert result == "line1\nline2\nline3"
assert result.count("\n") == 2
def test_multiline_two_lines():
result = make_multiline(["a", "b"])
assert "\n" in result
def test_tabbed():
result = make_tabbed("Name", "Alice")
assert result == "Name:\tAlice"
assert "\t" in result, "Missing tab character between label and value"
def test_path():
result = make_path()
assert result == "C:\\Users\\alice\\notes.txt"
assert "\\" in result, "Path must use \\\\ (escaped backslash), not \\U etc."
assert "\\U" not in result or result == "C:\\Users\\alice\\notes.txt"
def test_quoted():
result = make_quoted("Hello!")
assert result == 'He said: "Hello!"'
assert result.startswith('He said: "')
assert result.endswith('"')