gotchapythonMinorpending
Gotcha: Python f-strings with backslashes and expressions
Viewed 0 times
f-stringbackslashformat stringsyntax errorpep 701
Error Messages
Problem
Python f-strings have surprising limitations with backslashes and complex expressions that cause SyntaxError.
Solution
F-string limitations and workarounds:
# Backslashes NOT allowed inside f-string braces (before Python 3.12)
path = 'a\nb'
# BAD: SyntaxError
# f"Lines: {path.split('\n')}"
# GOOD: Use a variable
newline = '\n'
f"Lines: {path.split(newline)}"
# Or assign the result first
lines = path.split('\n')
f"Lines: {lines}"
# Python 3.12+ allows backslashes in f-strings!
# f"Lines: {path.split('\n')}" # Works in 3.12+
# Quotes inside f-strings
# BAD in Python < 3.12:
# f"{'hello'}" # Same quote type inside
# GOOD: Use different quotes
f"{'hello'}" # OK: different quotes
f'result: {d["key"]}' # OK: different quotes
f"""result: {d['key']}""" # OK: triple quotes
# Dictionary access in f-strings
d = {'name': 'Alice'}
f"Hello {d['name']}" # Works with single inside double
# f"Hello {d["name"]}" # SyntaxError before 3.12!
# Debugging with f-string = (Python 3.8+)
x = 42
f"{x = }" # "x = 42"
f"{x = :.2f}" # "x = 42.00"
f"{len('hello') = }" # "len('hello') = 5"
# Multi-line f-strings
message = (
f"Name: {name}\n"
f"Age: {age}\n"
f"Email: {email}"
)
# Format spec in f-strings
f"{value:>10}" # Right-align in 10 chars
f"{price:.2f}" # 2 decimal places
f"{count:,}" # Thousands separator: 1,234,567
f"{ratio:.1%}" # Percentage: 85.3%
f"{n:#010x}" # Hex with padding: 0x000000ffWhy
F-string restrictions exist because the parser processes the string before evaluating expressions. Python 3.12 lifted most of these restrictions with PEP 701.
Context
Python string formatting
Revisions (0)
No revisions yet.