SyntaxError
SyntaxError: f-string: expecting '}'
Traceback
Traceback (most recent call last):
File "main.py", line 1, in <module>
path = f"C:\Users\{name}\docs" # backslash issue pre-3.12
SyntaxError: f-string: expecting '}'What causes this error
An f-string contains an expression with invalid syntax. This includes unbalanced braces, backslashes (before Python 3.12), or complex expressions that the f-string parser cannot handle.
How to fix it
Extract complex expressions to variables before the f-string. Escape literal braces with {{ and }}. Upgrade to Python 3.12+ for relaxed f-string rules. Use .format() for complex cases.
Code that causes this error
path = f"C:\Users\{name}\docs" # backslash issue pre-3.12Fixed code
# Extract to variable:
user_dir = f"C:\\Users\\{name}\\docs"
# Or use a separate variable:
prefix = "C:\\Users"
path = f"{prefix}\\{name}\\docs"About SyntaxError
This SyntaxError occurs within f-string expressions when the expression inside the curly braces has invalid syntax. F-strings were introduced in Python 3.6 and allow embedding expressions directly in string literals. Common triggers for this error include using backslashes inside f-string expressions (not allowed before Python 3.12), unbalanced braces, using the walrus operator incorrectly, and complex expressions that confuse the parser.
Before Python 3.12, f-strings had significant limitations: no backslashes, no comments, and the same quote character could not be reused in nested expressions. Python 3.12 relaxed many of these restrictions with PEP 701, allowing backslashes, comments, and unlimited nesting of quote types. When debugging f-string errors, extract the expression to a separate variable as a workaround.
Common scenarios
Writing code with missing colons, parentheses, or brackets
Mixing Python 2 and Python 3 syntax when upgrading a codebase
Copy-pasting code from the web with formatting issues or invisible characters
Using reserved keywords as variable or function names