SyntaxError: f-string: empty expression not allowed (Python)

avatar

Borislav Hadzhiev

Sat Apr 30 20222 min read

SyntaxError: f-string: empty expression not allowed (Python) #

The Python "SyntaxError: f-string: empty expression not allowed" occurs when we have an empty expression in a formatted string literal. To solve the error, specify an expression between the curly braces of the f-string or use the str.format() method.

syntaxerror f string empty expression not allowed

Here is an example of how the error occurs.

main.py
name = 'Alice' my_str = f'employee: {}'.format(name) # ⛔️ SyntaxError: f-string: empty expression not allowed print(my_str)

We forgot to specify an expression or a variable name in the curly braces of the formatted string literal.

One way to solve the error is to move the name variable inside of the curly braces of the f-string.

main.py
name = 'Alice' my_str = f'employee: {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}.

Alternatively, you can use the str.format() method.

The str.format method performs string formatting operations.

main.py
first = 'James' last = 'Doe' result = "His name is {0} {1}".format(first, last) print(result) # 👉️ "His name is James Doe"

Notice that the string is not prefixed with f.

The string the method is called on can contain replacement fields specified using curly braces {}.

Each replacement field should contain either the numeric index of a position argument or the name of a keyword argument.

main.py
first = 'James' last = 'Doe' result = "His name is {f} {l}".format(f=first, l=last) print(result) # 👉️ "His name is James Doe"

The example above uses keyword arguments instead of position ones.

Make sure to provide exactly as many arguments to the format() method as you have replacement fields in the string.

If you decide to use positional arguments with numeric indices, make sure to start from 0, e.g. {0} as indices are zero-based in Python.

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