0

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

7
  • 6
    \ is an escape character, use raw strings or double \: line = line.replace(r"\", r"\\") ... and this doesn't work... Hmmm. Commented Oct 6, 2021 at 21:11
  • r"\" is a syntax error Commented Oct 6, 2021 at 21:13
  • r"\" is specifically not allowed for some reason, so line = line.replace("\\", "\\\\") as answered below Commented Oct 6, 2021 at 21:17
  • @dirck: You can't end a raw string with an unescaped backslash. Oddly, r'\\' seems to produce a string with two backslashes (even though the first isn't actually escaping the second). So you could do line = line.replace('\\', r'\\'), or you just do line =line.replace('\\', '\\\\') and avoid the confusion raw strings ending in slash involve. Commented Oct 6, 2021 at 21:17
  • @dirck: The reason it's not allowed is that backslash still escapes the quote mark, even in raw strings. So r"\" is viewed by the parser as a raw string beginning with a double-quote, and then it gets confused when the third double-quote closes the raw string (r"\", r" is treated as one literal), and it's followed by \ (which it thinks is a line continuation character), but then sees more on the same line after it. Commented Oct 6, 2021 at 21:19

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Thank you very much, your solution is working!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.