Python Glossary Русский

all Python 3refunction

re.escape()

escaping

Escape special characters in a string so it is matched literally — needed when a pattern is built from user input.

Syntax

re.escape(pattern) -> str

Reach for it exactly when part of the pattern is data: a file name, a word typed by the user, a separator held in a variable. Without escaping a dot, plus or bracket silently becomes a metacharacter, and an unbalanced bracket becomes an re.error. It does not cover the replacement string of re.sub(), which has its own rules — a \1 or \g<name> coming from data still acts as a group reference, so pass a function as repl instead.

Examples

import re
print(re.escape('1+1=2'))  # → 1\+1=2
print(re.escape('file.txt'))  # → file\.txt
print(re.escape('file.name (v2).txt'))  # → file\.name\ \(v2\)\.txt
print(re.escape('a|b|c'))  # → a\|b\|c
print(re.findall(re.escape('price (USD)'), 'price (USD) today'))  # → ['price (USD)']
print(re.compile(re.escape('c++')).search('i know c++') is not None)  # → True

See also

Open in the full glossarydocs.python.orgReport an inaccuracy