Borislav Hadzhiev
Mon Apr 25 2022·2 min read
Photo by Laura Gomez
The Python "SyntaxError: f-string expression part cannot include a backslash" occurs when we use a backslash between the curly braces of a formatted string. To solve the error, store the backslash character in a variable or move it out of the curly braces of the f-string.
Here is an example of how the error occurs.
first = 'James' last = 'Doe' # ⛔️ SyntaxError: f-string expression part cannot include a backslash result = f'{first\n}{last}'
We can't use a backslash in the expression part (the curly braces) of a formatted string literal.
One way to solve the error is to extract the \
or the \n
character in a
variable.
first = 'James' last = 'Doe' nl_char = '\n' * 2 result = f'{first}{nl_char}{last}' # James # Doe print(result)
If your use case doesn't require an expression, and all you have is a backslash
or a \n
char, move it out of the curly braces.
first = 'James' last = 'Doe' result = f'{first}\n{last}' # James # Doe print(result)
Here is another example of extracting a newline char in a variable, so we can use it in the expression of an f-string.
employees = ['Alice', 'Bob', 'Carl'] newline_char = '\n' my_str = f'Employees list: \n{newline_char.join(employees)}' # Employees list: # Alice # Bob # Carl print(my_str)
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}
.