Python – replace all “\” with “\\” python

pythonregex

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?

Best Solution

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