How to replace backslash character with empty string in python

I am trying to replace the backslash '\' in a string with the following code

string = "<P style='TEXT-INDENT'>\B7 </P>" result = string.replace("\",'') 

result:

 ------------------------------------------------------------ File "<ipython console>", line 1 result = string.replace("\",'') ^ SyntaxError: EOL while scanning string literal 

I don’t need backslashes here, because in fact I am parsing the xml file with the tag in the above format, therefore, if the backslash is displayed there invalid token during parsing

Can I learn how to replace backslash with empty string in python

+8
python replace
source share
5 answers
 result = string.replace("\\","") 
+11
source share

The error is that you did not add an escape character to your '\' , you must give \\ for backslash (\)

 In [147]: str = "a\c\d" In [148]: str Out[148]: 'a\\c\\d' In [149]: str.replace('\\', " ") Out[149]: 'acd' In [150]: str.replace('\\', "") Out[150]: 'acd' 
+4
source share
 >>> string = "<P style='TEXT-INDENT'>\B7 </P>" >>> result = string.replace("\\",'') >>> result "<P style='TEXT-INDENT'>B7 </P>" 
+1
source share

Just to give you an explanation: backslash \ has special meaning in many languages. In Python, taking a doc :

The backslash character () is used to delete characters that would otherwise have special meaning, such as a newline character, backslash character, or quotation mark character.

So, to replace \ with a string, you need to escape the backslash with "\\"

 >>> "this is a \ I want to replace".replace("\\", "?") 'this is a ? I want to replace' 
+1
source share

You need to escape the "\" with one extra backslash to compare it with \ . Therefore, you must use "\" ..

See Python Documentation - Section 2.4 for all escape sequences in Python .. And how you should deal with them.

0
source share

All Articles