Solve - SyntaxError: f-string: unmatched '(' in Python

avatar

Borislav Hadzhiev

Sat Apr 30 20222 min read

banner

Photo by Pradidpong

Solve - SyntaxError: f-string: unmatched '(' in Python #

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

syntaxerror f string unmatched

Here is an example of how the error occurs.

main.py
name = 'Alice' # ⛔️ SyntaxError: f-string: unmatched '(' print(f"employee: {name.replace("Alice", "Bob")}")

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

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

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

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

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

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 having a mismatch in opening and closing brackets.

main.py
name = 'Alice' # ⛔️ SyntaxError: f-string: unmatched ')' my_str = f'employee: {name)'

We opened the expression block with a curly brace but ended it with a parenthesis which caused the error.

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

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

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}.

Use the search field on my Home Page to filter through my more than 1,000 articles.