Home > Net >  How to replace "\" with "\\" in python?
How to replace "\" with "\\" in python?

Time:10-07

How to replace "\" with "\\" in python(type string)? I tried line = line.replace("\", "\\"), but it gives error SyntaxError: unexpected character after line continuation character

CodePudding user response:

In Python strings, \ is an escape, meaning something like, "do something special with the next character." The proper way of specifying \ itself is with two of them:

line = line.replace("\\", "\\\\")

Funny enough, I had to do the same thing to your post to get it to format properly.

CodePudding user response:

To replace \ with \\ in a Python string, you must write \\ in the Python string literal for each \ you want. Therefore:

line = line.replace("\\", "\\\\")

You can often use raw strings to avoid needing the double backslashes, but not in this case: r"\" is a syntax error, because the r modifier doesn't do what most people think it does. (It means both the backspace and the following character are included in the resulting string, so r"\" is actually a backslash followed by a quote, and the literal has no terminating quote!)

  • Related