Solve - SyntaxError: f-string: expecting '}' in Python

avatar

Borislav Hadzhiev

Last updated: Apr 30, 2022

banner

Photo from Unsplash

Solve - SyntaxError: f-string: expecting '}' in Python #

The Python "SyntaxError: f-string: expecting '}'" occurs when we use single quotes inside of an f-string that was wrapped using single quotes. To solve the error, make sure to wrap your f-string in double quotes if it contains single quotes and vice versa.

syntaxerror f string expecting

Here is an example of how the error occurs.

main.py
employees = ['Alice', 'Bob', 'Carl'] # ⛔️ SyntaxError: f-string: expecting '}' my_str = f'Employees list: \n{', '.join(employees)}' print(my_str)

We wrapped our f-string in single quotes but the string itself contains single quotes in the expression.

To solve the error, alternate the quotes. For example, if the f-string contains single quotes, wrap it in double quotes.

main.py
employees = ['Alice', 'Bob', 'Carl'] my_str = f"Employees list: \n{', '.join(employees)}" # Employees list: # Alice, Bob, Carl print(my_str)

Conversely, if the string contains double quotes, wrap it in single quotes.

main.py
employees = ['Alice', 'Bob', 'Carl'] my_str = f'Employees list: \n{", ".join(employees)}' # Employees list: # Alice, Bob, Carl print(my_str)

You can use a triple-quoted string if your f-string contains both double and single quotes.

main.py
name = 'Alice' # 👇️ employee's name: Bob print(f"""employee's name: {name.replace("Alice", "Bob")}""")

Another common cause of the error is to forget to close an expression block with a curly brace.

main.py
employees = ['Alice', 'Bob', 'Carl'] # ⛔️ SyntaxError: f-string: expecting '}' my_str = f'Employees list: \n{", ".join(employees)'

We opened the expression block using a curly brace but forgot to close it.

Expression blocks need to be opened and closed using curly braces.

main.py
employees = ['Alice', 'Bob', 'Carl'] # ⛔️ SyntaxError: f-string: expecting '}' my_str = f'Employees list: \n{", ".join(employees)}' # Employees list: # Alice, Bob, Carl print(my_str)

If you are trying to access a key in a dictionary or an item in a list, use square brackets.

main.py
emp = {'name': 'Alice'} my_str = f"employee: {emp['name']}" print(my_str) # 👉️ employee: Alice

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

main.py
my_str = 'is subscribed:' my_bool = True result = f'{my_str} {my_bool}' print(result) # 👉️ is subscribed: True

Make sure to wrap expressions in curly braces - {expression}.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.