replace all "\" with "\\" python


Question

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?

1
14
6/26/2011 10:42:44 PM

Accepted Answer

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
21
6/26/2011 10:09:32 PM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon