0

Here are numerous examples where backslash is removed from. Unfortunately non is working

I have string like that

item = '^^\n^'

this should work

item = item.replace('\\\\n^', '')

for the expected result '^^' but the item stays as it is.

Python Version is 3.8.3. Any hint why it should not work ?

user3732793
  • 1,699
  • 4
  • 24
  • 53
  • 3
    Shouldn't `item.replace('\n^', '')` work? The backslash in the original string isn't escaped either. – kwkt Jan 15 '21 at 10:40
  • 1
    You can't remove something that's not even there in the first place. – superb rain Jan 15 '21 at 10:45
  • @kwt no the backslash is used for escaping. so item.replace('\\n^', '') should but doesn't either for some wired reason – user3732793 Jan 15 '21 at 11:06
  • @user3732793 Per my answer below, you do not need an escape character. kwkt's example is correct. Try running it in your terminal. – tnknepp Jan 15 '21 at 11:12

1 Answers1

3

You ask why this does not work. It doesn't work because "\n" is a single character not two characters. Check it out:

In [7]: len("\n")                                                                                                                                 
Out[7]: 1

Therefore, Python recognizes the backslash in "\n" not as a escape character, but part of the single character itself. If you want to keep the backslash, but lose the "n", you need to target the "\n" completely.

In [15]: item.replace("\n", "\\")                                                                                                                 
Out[15]: '^^\\^'

But that doesn't work, we now have two backslashes in the string, right? Wrong, one of them is escaped!

In [16]: print(item.replace("\n", "\\"))                                                                                                          
^^\^

Escape characters can be tricky if you don't use them often. I refresh my memory, when needed, with simple examples in IPython.

Per kwkt's comment, the solution is:

In [1]: item = '^^\n^'
In [2]: item.replace('\n^', '')                                                                                                                   
Out[2]: '^^'
tnknepp
  • 5,888
  • 6
  • 43
  • 57