>>> print 'aaa\rbbb'.replace('\r','ccc')
aaacccbbb
>>> print 'aaa\rbbb'.replace('\\r','ccc')
bbb
>>> print 'aaa\rbbb'.replace(r'\r','ccc')
bbb
>>>
I am wondering a reason for last two statment. and I am confusing what
>>> print 'aaa\rbbb'.replace('\r','ccc')
aaacccbbb
>>> print 'aaa\rbbb'.replace('\\r','ccc')
bbb
>>> print 'aaa\rbbb'.replace(r'\r','ccc')
bbb
>>>
I am wondering a reason for last two statment. and I am confusing what
The last two variations do not replace the line return character, so it prints out the original 'aaa\rbbb'
. It first prints aaa
, then the line return character, moving the cursor back to the beginning of the line, and then it prints bbb
over the existing aaa
.
The reason '\\r'
and r'\r'
don't replace '\r'
is because '\r'
is the line return character, but both '\\r'
and r'\r'
are a backslash followed by the letter "r".
That's because '\\r'
is literally the character '\'
followed by the character 'r'
The same for r'\r'
. the r
prefix is used for raw strings.
Both won't match the character \r
(because it's a single character)