Replace \\ with / Python
This doesn't work:
import re
re.sub('\\', '/', "C:\\Users\\Judge")
Error:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
re.sub('\\', '开发者_Go百科/', "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)
Try escaping two backslashes instead of one: \\\\
re.sub('\\\\', '/', "C:\\Users\\Judge")
You are just passing the RE engine one backslash, which confuses it. So, not only do you have to escape the backslashes for Python to be happy, you need to escape it again for RE. Since you are escaping two backslashes, you need four total.
If you aren't using any regular expression features, perhaps you'd be better off with string's simpler replace method:
'C:\\Users\\Judge'.replace('\\', '/')
You don't need a regular expression for such a simple substitution. And the quoting becomes easier then:
"C:\\Users\\Judge".replace("\\", "/")
You can also use raw strings:
re.sub(r'\\', '/', 'C:\\Users')
Note the r in front of the search string which interprets backslashes differently from ordinary strings. That is, control sequences like \n will be taken literally, i.e. as backslash followed by n instead of a newline.
"C:\\Users\\Judge".replace('\\', '/')
As for regex patterns, use r'\\'
You need to use \\\\
:
re.sub('\\\\', '/', "C:\\Users\\Judge")
Or use the r modifier:
re.sub(r'\\', '/', "C:\\Users\\Judge")
See Python documentation on re.
Assuming you want to normalize your path, and not just generally asking how to turn backslashes into forward ones, you can use the path.normpath()
instead. Granted it may not work exactly as you expect, because you are trying to convert away from the windows-form, but consider this sample:
import os2emxpath as path
print path.normpath("C:\\windows\\hello")
prints
C:/windows/hello
EDIT As Oben points out in the comments the backslash-ed string is the correct form for windows, so it should work for most of your needs. However if you want to mangle that to some other form, you could just import the corresponding path module.
精彩评论