Understand Python re.escape() Function for Beginners – Python Tutorial

By | August 29, 2019

Python regression expression re.escape(pattern) function can escape special characters in pattern, in this tutorial, we will introduce how to use this function correctly for python beginners.

Syntax of function

re.escape(pattern)

Python regression expression special characters contains: ., +, , (, ) et al. If these special characters are in pattern, you should use ‘\‘ to escape them.

For exampe,

If there is a string:  python learing (pdf). You want to remove (pdf). The pattern should be:

pattern = '\(pdf\)'

You can use this pattern to remove this string like:

str = "python learing (pdf)"
pattern = "\(pdf\)"
str = re.sub(pattern, '', str, flags=re.IGNORECASE)
print(str)

The result is:

python learing

However, if you do not want to use ‘\‘ to escape especial characters in pattern manully, How to do?

Use re.escape() to escapge especial characters

Escape especial characters

pattern = "(pdf)"
pattern = re.escape(pattern)
print(pattern)

The pattern is:

\(pdf\)

Replace string

str = re.sub(pattern, '', str, flags=re.IGNORECASE)
print(str)

The result is:

python learing

Leave a Reply