Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python replace forward slash with back slash

Tags:

python

regex

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.

like image 498
synaptik Avatar asked Jan 31 '13 21:01

synaptik


2 Answers

The second argument should be a string, not a regex pattern:

foo.replace(r'/DIR/', '\\\\MYDIR\\data\\')
like image 140
Explosion Pills Avatar answered Sep 20 '22 13:09

Explosion Pills


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
like image 31
Serdalis Avatar answered Sep 20 '22 13:09

Serdalis