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.
The second argument should be a string, not a regex pattern:
foo.replace(r'/DIR/', '\\\\MYDIR\\data\\')
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
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