Python SyntaxError: f-string: expecting '}'
Python SyntaxError: f-string: expecting '}'
This exception "SyntaxError: f-string: expecting '}'" occurs when we using formatted string, and the variable or expression in the formatted string is not ended with the closing curly brace }
.
Let us recreate this exception by using a formatted string, and not ending the variable with closing curly brace.
Python Program
# Given variable
name = "Apple"
# Formatted string
result = f"Hello {name!"
# Print resulting string
print(result)
Output
File "/Users/pythonexamples_org/workspace/main.py", line 5
result = f"Hello {name!"
^
SyntaxError: f-string: expecting '}'
Solution
The solution is straight forward. We have to enclose the variable or expression in curly braces. Place the ending curly brace, and the exception is gone.
Python Program
# Given variable
name = "Apple"
# Formatted string
result = f"Hello {name}!"
# Print resulting string
print(result)
Output
Hello Apple!
That's it! This is how we resolve the Python exception "SyntaxError: f-string: expecting '}'".
Summary
In this tutorial, we solved the exception "SyntaxError: f-string: expecting '}'" by writing the trailing curly brace after the variable or expression used in the formatted string.