Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing an backslash from a string [duplicate]

Tags:

python

nltk

I have a string that is a sentence like I don't want it, there'll be others

So the text looks like this I don\'t want it, there\'ll be other

for some reason a \ comes with the text next to the '. It was read in from another source. I want to remove it, but can't. I've tried. sentence.replace("\'","'")

sentence.replace(r"\'","'")

sentence.replace("\\","")

sentence.replace(r"\\","")

sentence.replace(r"\\\\","")

I know the \ is to escape something, so not sure how to do it with the quotes

like image 505
jason Avatar asked Oct 16 '15 11:10

jason


2 Answers

The \ is just there to escape the ' character. It is only visible in the representation (repr) of the string, it's not actually a character in the string. See the following demo

>>> repr("I don't want it, there'll be others")
'"I don\'t want it, there\'ll be others"'

>>> print("I don't want it, there'll be others")
I don't want it, there'll be others
like image 106
Cory Kramer Avatar answered Sep 22 '22 12:09

Cory Kramer


Try to use:

sentence.replace("\\", "")

You need two backslashes because first of them act as escape symbol, and second is symbol that you need to replace.

like image 41
Eugene Soldatov Avatar answered Sep 18 '22 12:09

Eugene Soldatov