6

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.

synaptik
  • 8,971
  • 16
  • 71
  • 98

5 Answers5

6

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

foo.replace(r'/DIR/', '\\\\MYDIR\\data\\')
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
3

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
Serdalis
  • 10,296
  • 2
  • 38
  • 58
3

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

inv_num = line.replace(r'/', '-')
Ramesh-X
  • 4,853
  • 6
  • 46
  • 67
0

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.
nneonneo
  • 171,345
  • 36
  • 312
  • 383
0

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

Andy
  • 1
  • 2
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 27 '22 at 06:43