3

code goes below:

line = r'abc\def\n'
rline = re.sub('\\\\', '+', line) # then rline should be r'abc+def+n'

Apparently, I just want to replace the backslashes in line with '+'. What I thought was that a backslash in line can be expressed as '\', then why should I use '\\' to get the re.sub work right.

I'm confused.

2
  • 1
    Why not just use rline = line.replace('\\', '+')? Commented Aug 16, 2011 at 11:46
  • @nagisa -- ya, that's a way circumventing the problem, but I want to know why re.sub doesn't work that way. Commented Aug 16, 2011 at 12:53

3 Answers 3

7

It's a good habit to always use raw strings when dealing with regex patterns:

In [45]: re.sub(r'\\', r'+', line)
Out[45]: 'abc+def+n'

To answer your question though, Python interprets '\\\\' as two backslash characters:

In [44]: list('\\\\')
Out[44]: ['\\', '\\']

And the rules of regex interpret two backslash characters as one literal backslash.

Sign up to request clarification or add additional context in comments.

Comments

4

Because there are two levels of backslashing:

  1. re.sub uses \ as an escape
  2. Python uses \ as an escape (unless you do r'...')

So \\\\ (python) -> \\ (re.sub) -> \

EDIT

And the SO level of backslashing! (it got me!)

6 Comments

+1 for cleverness -1 for not using backticks to format code properly. :P.
formatted with backticks, doesn't require additional backslashing ;)
I didn't edit it since he made a point of getting it "right" without.
@Owen -- It seems like your answer pretty much convince me. Hah.
and one more question, what do you mean by SO level ?
|
2

If you want to search for a literal pattern, not an actual regular expression, you should use both raw strings and re.escape() to avoid doubling backslashes or any other manual escaping completely.

So, your example would become:

line = r'abc\def\n'
backslash = re.escape(r'\')
rline = re.sub(backslash, '+', line)

1 Comment

Hmm, apparently the SO syntax highlighter doesn't like raw strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.