开发者

replace all "\" with "\\" python

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

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

But it screws it up because of the escape seq开发者_运维知识库uence. does anyone know the awnser to my question?


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.


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\\\\


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜