Last updated: Apr 8, 2024
Reading timeยท2 min
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.
Here is an example of how the error occurs.
name = 'Bobby' 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.
name = 'Bobby' my_str = f'employee: {name}' print(my_str) # ๐๏ธ employee: Bobby
Formatted string literals (f-strings) let us include expressions inside of a
string by prefixing the string with f
.
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}
.
You can also evaluate expressions directly in the curly braces.
num = 100 name = 'Bobby' result = f'Salary = {num * 2}, Name: {name.upper()}' print(result) # ๐๏ธ Salary = 200, Name: BOBBY
Alternatively, you can use the str.format()
method.
str.format()
method instead of a formatted string literalThe str.format() method performs string formatting operations.
first = 'Bobby' last = 'Hadz' result = "His name is {} {}".format(first, last) print(result) # ๐๏ธ "His name is Bobby Hadz"
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 can contain the numeric index of a positional argument or the name of a keyword argument.
first = 'Bobby' last = 'Hadz' result = "His name is {f} {l}".format(f=first, l=last) print(result) # ๐๏ธ "His name is Bobby Hadz"
The example above uses keyword arguments instead of positional ones.
format()
method as you have replacement fields in the string.Here is an example of a hacky way to solve the error.
name = 'Bobby' result = f'Name: {{}}'.format(name) print(result) # ๐๏ธ Name: Bobby
We used 2 sets of curly braces.
Technically, the expression is not empty, so an error isn't raised.
We then called the str.format()
to replace the curly braces with the value of
the name
variable.
However, this syntax is confusing and should be avoided as using only f-strings
or the str.format()
method is much easier to read.
I've also written an article on how to use f-strings for conditional formatting.
You can learn more about the related topics by checking out the following tutorials: