Fixing "escape Sequence Not Allowed In Expression Portion Of F-string" Errors In Python

January 26, 2024

Woman Programming on a Notebook
Photo by Christina Morillo on Pexels.

Introduction

Python is a versatile and powerful programming language that is widely used in various domains. One of the key features of Python is the f-string, introduced in Python 3.6, which provides a concise and convenient way to format strings. However, when working with f-strings, you may encounter an error that says "Escape sequence not allowed in expression portion of f-string". In this article, we will explore the causes of this error and learn how to fix it.

What is an f-string?

Before diving into the error, let's briefly discuss what an f-string is. An f-string is a literal string prefixed with the letter 'f' or 'F'. It allows you to embed expressions inside curly braces, which are then evaluated and formatted into the final string. For example:

name = 'John'
age = 25
print(f'My name is {name} and I am {age} years old')

This will output: 'My name is John and I am 25 years old'.

Understanding the error

The "Escape sequence not allowed in expression portion of f-string" error occurs when you try to include an escape sequence, such as '\n' or '\t', within the expression portion of an f-string. For example:

print(f'My name is {name} and I am {age} years old.\n')

This will result in an error message:

SyntaxError: (unicode error) '\n' in position 35: Escape sequence not allowed in expression portion of f-string

The error message indicates that the escape sequence '\n' is not allowed within the expression portion of the f-string.

Fixing the error

To fix the "Escape sequence not allowed in expression portion of f-string" error, you can use a raw string inside the expression portion of the f-string. A raw string, denoted by the 'r' prefix, treats escape sequences as literal characters. For example:

print(f'My name is {name} and I am {age} years old.\n')

can be fixed by using a raw string:

print(f'My name is {name} and I am {age} years old.\n'.replace(r'\n', '\n'))

This will output the desired result: 'My name is John and I am 25 years old.

Conclusion

In this article, we explored the causes of the "Escape sequence not allowed in expression portion of f-string" error in Python. We learned that this error occurs when you try to include an escape sequence within the expression portion of an f-string. However, with a simple fix using a raw string, we can overcome this error and continue using f-strings effectively in our Python code.