Answer a question

I am trying replace a 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

Here i don't need the back slashes because actually i am parsing an xml file which has a tag in the above format, so if backslashes are there it is displaying invalid token during parsing

Can i know how to replace the backslashes with empty string in python

Answers

We need to specify that we want to replace a string that contains a single backslash. We cannot write that as "\", because the backslash is escaping the intended closing double-quote. We also cannot use a raw string literal for this: r"\" does not work.

Instead, we simply escape the backslash using another backslash:

result = string.replace("\\","")
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐