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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With