Replace \\ with / Python

This does not work:

import re
re.sub('\\', '/', "C:\\Users\\Judge")

Error:

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    re.sub('\\', '/', "C:\\Users")
  File "C:\Python27\lib\re.py", line 151, in sub
    return _compile(pattern, flags).sub(repl, string, count)
  File "C:\Python27\lib\re.py", line 244, in _compile
    raise error, v # invalid expression
error: bogus escape (end of line)
+5
source share
6 answers

Try avoiding two backslashes instead of one: \\\\

re.sub('\\\\', '/', "C:\\Users\\Judge")

You just give the RE engine one backslash, which confuses it. Thus, you not only need to avoid backslashes for Python, to be happy, you need to escape from it again for RE. Since you avoid two backslashes, you only need four.

If you are not using any of the regular expression functions, you might be better off using the simplified string replacement method:

'C:\\Users\\Judge'.replace('\\', '/')

+7
source

You do not need a regex for such a simple substitution. And the quote becomes simpler:

"C:\\Users\\Judge".replace("\\", "/")
+4

:

re.sub(r'\\', '/', 'C:\\Users')

r , , . , \n, , .. , n .

+2
"C:\\Users\\Judge".replace('\\', '/')

, r'\\'

+1

, , , , path.normpath(). , , , , :

import os2emxpath as path
print path.normpath("C:\\windows\\hello")

C:/Windows/

EDIT As Aubin points out in the comments, a backslash line is the correct form for windows, so it should work for most of your needs. However, if you want to use this for some other form, you can simply import the corresponding path module.

+1
source

You need to use \\\\:

re.sub('\\\\', '/', "C:\\Users\\Judge")

Or use the r modifier :

re.sub(r'\\', '/', "C:\\Users\\Judge")

See the Python documentation for re .

+1
source

All Articles