14

Does anyone know how replace all \ with \\ in python? Ive tried:

re.sub('\','\\',string)

But it screws it up because of the escape sequence. does anyone know the awnser to my question?

5
  • 3
    mywiki.wooledge.org/XyProblem Commented Jun 26, 2011 at 21:43
  • @gnibbler r'\' is not valid. Commented Jun 26, 2011 at 22:00
  • @JBernardo, heh, I just realised an deleted that comment, still why not just use the str method instead of regex? ie. string.replace('\\',r'\\') Commented Jun 26, 2011 at 22:02
  • @gnibbler As @Ignacio wrote, probably it isn't OP's real question... Maybe he's having trouble with windows paths or CRLF Commented Jun 26, 2011 at 22:10
  • @JBernardo, ah in that case, telling the OP that '/' works fine (instead of '\') in windows paths may or may not help :) Commented Jun 26, 2011 at 22:15

4 Answers 4

22

You just need to escape the backslashes in your strings: (also there's no need for regex stuff)

>>> s = "cats \\ dogs"
>>> print s
cats \ dogs
>>> print s.replace("\\", "\\\\")
cats \\ dogs
Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't work. You either need re.sub("\\\\","\\\\\\\\",string) or re.sub(r'\\', r'\\\\', string) because you need to escape each slash twice ... once for the string and once for the regex.
7

you should do:

re.sub(r'\\', r'\\\\', string)

As r'\' is not a valid string

BTW, you should always use raw (r'') strings with regex as many things are done with backslashes.

3 Comments

This doesn't work. You either need re.sub("\\\\","\\\\\\\\",string) or re.sub(r'\\', r'\\\\', string) because you need to escape each slash twice ... once for the string and once for the regex.
Still doesn't work. You are trying to replace a literal \ with the first part of a regex escape for special character, so it complains: "error: unexpected end of regular expression"
@ecounysis You're totally right. I hadn't tried in the interpreter... :(
3

You should escape backslashes, and also you don't need regex for this simple operation:

>>> my_string = r"asd\asd\asd\\"
>>> print(my_string)
asd\asd\asd\\
>>> replaced = my_string.replace("\\", "\\\\")
>>> print(replaced)
asd\\asd\\asd\\\\

1 Comment

This does work in the interpreter, but fails when I run in the program. Weird. May be I'm doing something stupid.
3

You either need re.sub("\\\\","\\\\\\\\",string) or re.sub(r'\\', r'\\\\', string) because you need to escape each slash twice ... once for the string and once for the regex.

>>> whatever = r'z\w\r'
>>> print whatever
z\w\r
>>> print re.sub(r"\\",r"\\\\", whatever)
z\\w\\r
>> print re.sub("\\\\","\\\\\\\\",whatever)
z\\w\\r

Comments

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.