gotchapythonModeratepending
Gotcha: Python f-string cannot contain backslash in expression
Viewed 0 times
f-stringbackslashSyntaxErrornewlinejoin
Error Messages
Problem
Using backslash characters inside f-string curly braces raises a SyntaxError.
Solution
Backslashes are not allowed in f-string expressions:
# BAD - SyntaxError:
f"{'\n'.join(items)}" # Can't use \n in {}
f"{'\t'.join(items)}" # Can't use \t in {}
f"{path.replace('\\', '/')}" # Can't use \\ in {}
# GOOD - assign to variable first:
newline = '\n'
f"{newline.join(items)}"
# GOOD - use chr():
f"{chr(10).join(items)}" # chr(10) = newline
# GOOD - use a function:
def join_lines(items):
return '\n'.join(items)
f"{join_lines(items)}"
# GOOD - use str.join outside f-string:
result = '\n'.join(f"{item}: {value}" for item, value in pairs)
# Python 3.12+ FIXES THIS:
# f"{'\n'.join(items)}" # Works in Python 3.12+!
# Other f-string limitations (fixed in 3.12):
# - No reuse of same quote type
# f"{'hello'}" # OK
# f"{'he"llo'}" # SyntaxError before 3.12
# - No nested f-strings with same quotes
# f"{f'{x}'}" # SyntaxError before 3.12
# BAD - SyntaxError:
f"{'\n'.join(items)}" # Can't use \n in {}
f"{'\t'.join(items)}" # Can't use \t in {}
f"{path.replace('\\', '/')}" # Can't use \\ in {}
# GOOD - assign to variable first:
newline = '\n'
f"{newline.join(items)}"
# GOOD - use chr():
f"{chr(10).join(items)}" # chr(10) = newline
# GOOD - use a function:
def join_lines(items):
return '\n'.join(items)
f"{join_lines(items)}"
# GOOD - use str.join outside f-string:
result = '\n'.join(f"{item}: {value}" for item, value in pairs)
# Python 3.12+ FIXES THIS:
# f"{'\n'.join(items)}" # Works in Python 3.12+!
# Other f-string limitations (fixed in 3.12):
# - No reuse of same quote type
# f"{'hello'}" # OK
# f"{'he"llo'}" # SyntaxError before 3.12
# - No nested f-strings with same quotes
# f"{f'{x}'}" # SyntaxError before 3.12
Why
Before Python 3.12, the f-string parser couldn't handle backslashes in expressions. Python 3.12 rewrote the parser to lift this restriction.
Revisions (0)
No revisions yet.