-1
>>> 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

Z.Lun
  • 247
  • 1
  • 2
  • 20
  • 1
    If you are only just learning the basics, you should probably concentrate on the currently recommended and supported version of the language, which is Python 3. Python 2 was end-of-lifed earlier in 2020, but was originally slated to die in 2018. – tripleee Aug 06 '20 at 09:13
  • @tripleee Because of the incompatibility, I think they are two languages. I just encountered this problem when I was troubleshooting the problem. I tested the same result in python3. I am not trying to struggle with the language version.lol – Z.Lun Aug 06 '20 at 09:18
  • last two versions don't replace `\r` so it moves cursor to beginning of line and `bbb` replaces `aaa` . You get the same with `print 'aaa\rbbb'` without `replace()`. `'\\r'` and `r'\r'` don't mean special char `\r` but normal string with two chars `\ ` and `r` – furas Aug 06 '20 at 11:37

2 Answers2

3

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".

deceze
  • 510,633
  • 85
  • 743
  • 889
1

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)

Cid
  • 14,968
  • 4
  • 30
  • 45