Python Forum

Full Version: regular expression
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi

How can one escape the "\" character?

Escaping the "^" character works fine

>>> import re
>>> re.findall(re.escape("^"), "^hello^")
['^', '^']
But when escaping the "\" character I get an error:
>>> re.findall(re.escape("\"), "\hello\")
  File "<stdin>", line 1
    re.findall(re.escape("\"), "\hello\")
Thanks

Hi

discovered the answer here
From Python documentation: re - Regular expression operations::

Quote:The solution is to use Python’s raw string notation for regular expression patterns; backslashes are not handled in any special way in a string literal prefixed with 'r'. So r"\n" is a two-character string containing '\' and 'n', while "\n" is a one-character string containing a newline. Usually patterns will be expressed in Python code using this raw string notation.