SyntaxError: f-string expression part cannot include a backslash

avatar

Borislav Hadzhiev

Last updated: Apr 25, 2022

banner

Photo from Unsplash

SyntaxError: f-string expression part cannot include a backslash #

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.

syntaxerror f string expression part cannot include a backslash

Here is an example of how the error occurs.

main.py
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.

main.py
first = 'James' last = 'Doe' nl_char = '\n' * 2 result = f'{first}{nl_char}{last}' # James # Doe print(result)
A backslash character cannot be directly in the expression part of an f-string, but we can extract it in a variable and interpolate the variable in the string.

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.

main.py
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.

main.py
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.

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

Conclusion #

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.

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.