Reputation: 9539
I have
foo = '/DIR/abc'
and I want to convert it to
bar = '\\MYDIR\data\abc'
So, here's what I do in Python:
>>> foo = '/DIR/abc'
>>> bar = foo.replace(r'/DIR/',r'\\MYDIR\data\')
File "<stdin>", line 1
bar = foo.replace(r'/DIR/',r'\\MYDIR\data\')
^
SyntaxError: EOL while scanning string literal
If, however, I try to escape the last backslash by entering instead bar = foo.replace(r'/DIR/',r'\\MYDIR\data\\')
, then I get this monstrosity:
>>> bar2
'\\\\MYDIR\\data\\\\abc'
Help! This is driving me insane.
Upvotes: 7
Views: 36999
Reputation: 1
path=path.replace(r"/","\") will replace path=C:/folder with path=C:\folder
Upvotes: 0
Reputation: 35
I simply put a r
in front of /
to change the forward slash.
inv_num = line.replace(r'/', '-')
Upvotes: 4
Reputation: 191809
The second argument should be a string, not a regex pattern:
foo.replace(r'/DIR/', '\\\\MYDIR\\data\\')
Upvotes: 7
Reputation: 179717
Two problems:
'\\\\MYDIR\\data\\'
.repr
style), strings will appear with escapes. Therefore, '\\\\'
only has two actual backslashes. So, '\\\\MYDIR\\data\\\\abc'
is really \\MYDIR\data\\abc
.Upvotes: 0
Reputation: 10489
The reason you are encountering this is because of the behavior of the r""
syntax, Taking some explanation from the Python Documentation
r"\"" is a valid string literal consisting of two characters: a backslash and a double quote; r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character).
So you will need to use a normal escaped string for the last argument.
>>> foo = "/DIR/abc"
>>> print foo.replace(r"/DIR/", "\\\\MYDIR\\data\\")
\\MYDIR\data\abc
Upvotes: 3