medovi40k
medovi40k

Reputation: 3

How to replace "\" with "\\" in python?

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

Upvotes: 0

Views: 845

Answers (2)

kindall
kindall

Reputation: 184455

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!)

Upvotes: 1

Fred Larson
Fred Larson

Reputation: 62123

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.

Upvotes: 3

Related Questions