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?
The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With