SyntaxError: f-string expression cannot include backslash
Quick summary
You used a backslash inside the curly braces of an f-string expression — Python 3.11 and earlier rejects this with a SyntaxError.
Why this happens
You used a newline escape \n or other backslash escape inside f-string curly braces like f'{x\n}'
You tried to use a backslash in a nested string within an f-string expression part
Your f-string expression includes a raw string or escape sequence that contains a backslash
Minimal example
name = 'World'
msg = f'{name}\n' # works (backslash outside braces)
msg = f'{name.upper()}\n' # works
msg = f'{"hello\n" + name}' # SyntaxError in Python < 3.12name = 'World'
greeting = 'hello\n' + name # compute outside f-string
msg = f'{greeting}' # interpolate the resultMoving the backslash-containing expression to a variable before the f-string avoids the SyntaxError on Python 3.11 and earlier.
How to diagnose
Check the Python version — Python 3.12+ allows backslashes in f-string expressions (PEP 701)
Identify the backslash inside the curly braces of the f-string that triggers the SyntaxError
Move the expression with the backslash outside the f-string and interpolate the result instead
How to fix
Extract the expression to a variable before the f-string and interpolate the variable instead
Use string concatenation or .format() instead of f-strings for expressions that require backslashes
Upgrade to Python 3.12+ where backslashes are allowed inside f-string expressions
How to prevent
Avoid using backslashes directly inside f-string expressions — compute values in variables first
Use a linter that detects f-string SyntaxErrors before runtime on Python 3.11 and earlier