Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[python]: problem about python string literals

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.

like image 425
Alcott Avatar asked Jan 25 '26 06:01

Alcott


1 Answers

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.

like image 60
unutbu Avatar answered Jan 27 '26 19:01

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!