SyntaxError: f-string expression part cannot include a backslash

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
3 min

banner

# 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 = 'Bobby' last = 'Hadz' # โ›”๏ธ SyntaxError: f-string expression part cannot include a backslash result = f'{first\n}{last}'

backslash not allowed in f string

We can't use a backslash in the expression part (the curly braces) of a formatted string literal.

# Extract the backslash into a variable

One way to solve the error is to extract the \ or the \n character into a variable.

main.py
first = 'Bobby' last = 'Hadz' nl_char = '\n' * 2 result = f'{first}{nl_char}{last}' # Bobby # Hadz print(result)

extract backslash into variable

A backslash character cannot be directly in the expression part of an f-string.

However, we can extract the backslash into a variable and interpolate the variable in the string.

main.py
backslash = '\\' first = 'Bobby' last = 'Hadz' a_str = f'{backslash} {first} {backslash} {last}' print(a_str) # \ Bobby \ Hadz

As shown in this thead, backslashes inside brackets are disallowed in Python.

# Move the backslash out of the curly braces

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 = 'Bobby' last = 'Hadz' result = f'{first}\n{last}' # Bobby # Hadz print(result)

move backslash out of curly braces

The code sample only uses a backslash to add a newline \n character to the f-string, so there is no good reason for the backslash to be in the expression {} fields.

Here is another example of extracting a newline character into 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)

We called the str.join() method on the newline character.

Notice that we declared a variable and set it to a newline \n character to be able to use the character in an expression {} field.

# Using the chr() function to insert a backslash or newline char into an f-string

You can also use the chr() function to insert a backslash into the expression {} part of an f-string.

main.py
first = 'Bobby' last = 'Hadz' a_str = f'{chr(92)} {first} {chr(92)} {last}' print(a_str) # \ Bobby \ Hadz

using chr function to insert backslash into f string

The chr function returns the string representing the character at the given Unicode code point.

main.py
print(chr(92)) # ๐Ÿ‘‰๏ธ \ print(chr(92)) # ๐Ÿ‘‰๏ธ \ print(chr(8364)) # ๐Ÿ‘‰๏ธ โ‚ฌ

You can use chr(10) if you need to insert a newline \n character into the f-string.

main.py
first = 'Bobby' last = 'Hadz' a_str = f'{chr(10)} {first} {chr(10)} {last}' # Bobby # Hadz print(a_str)

# Using os.linesep() instead of \n

You can also use the os.linesep attribute if you need to add a newline character to a string.

main.py
import os my_str = f"bobby{os.linesep}hadz" # bobby # hadz print(my_str)

The os.linesep attribute returns the string that is used to separate lines on the current platform.

For example \n on Unix and \r\n on Windows.

# How formatted string literals work in Python

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

# Using the str.format() method instead of a formatted string literal

You can also use the str.format() method instead of a formatted string literal.

main.py
first = 'Bobby' last = 'Hadz' result = 'Name: {}{}'.format(first + '\n', last) # Name: Bobby # Hadz print(result)

No backslashes are used inside the curly braces, so the error is no longer raised.

The str.format() method performs string formatting operations.

main.py
first = 'bobby' last = 'hadz' result = "Name: {} {}".format(first, last) print(result) # ๐Ÿ‘‰๏ธ "Name: bobby hadz"

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

I've also written an article on how to use f-strings for conditional formatting.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev