synaptik
synaptik

Reputation: 9539

Python replace forward slash with back slash

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

Answers (5)

Andy
Andy

Reputation: 1

path=path.replace(r"/","\") will replace path=C:/folder with path=C:\folder

Upvotes: 0

Wen-Shan Wendy Chow
Wen-Shan Wendy Chow

Reputation: 35

I simply put a r in front of / to change the forward slash.

inv_num = line.replace(r'/', '-')

Upvotes: 4

Explosion Pills
Explosion Pills

Reputation: 191809

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

foo.replace(r'/DIR/', '\\\\MYDIR\\data\\')

Upvotes: 7

nneonneo
nneonneo

Reputation: 179717

Two problems:

  1. A raw literal simply cannot end with a single backslash because it is interpreted as escaping the quote character. Therefore, use a regular (non-raw) literal with escapes: '\\\\MYDIR\\data\\'.
  2. When displayed (using the repr style), strings will appear with escapes. Therefore, '\\\\' only has two actual backslashes. So, '\\\\MYDIR\\data\\\\abc' is really \\MYDIR\data\\abc.

Upvotes: 0

Serdalis
Serdalis

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

Related Questions