Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
regular expression
#1
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
Reply
#2
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.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [split] [split] regular expression kerzol81 1 3,466 Jun-24-2018, 09:18 AM
Last Post: volcano63
  [split] regular expression metalray 2 3,125 Jun-15-2018, 01:22 AM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020