Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace all "\" with "\\" python

Tags:

python

regex

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?

like image 959
P'sao Avatar asked Jun 26 '11 21:06

P'sao


People also ask

How do you replace all characters in Python?

The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.

How do you replace all occurrences of a string in Python?

Python String replace() Method The replace() method replaces a specified phrase with another specified phrase. Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.

Is there a replace all function in Python?

The replace() method is a built-in functionality offered in Python programming. It replaces all the occurrences of the old substring with the new substring. Replace() returns a new string in which old substring is replaced with the new substring.

Can you replace multiple things at once in Python?

02) Using replace() with ListsThe replace() method can also be used to replace multiple (different) characters with another (same or different for each) character. Using the for loop: The most common way of working with lists is using the for a loop.


2 Answers

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
like image 98
bradley.ayers Avatar answered Sep 21 '22 18:09

bradley.ayers


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.

like image 39
JBernardo Avatar answered Sep 18 '22 18:09

JBernardo