-2

Edited question: I am writing a python function that takes the string of a path as copy-pasted from windows (so with backslashes) and returns a string with forwardslashes, that can be used by python as a path. The problem arises with the combination of backlashes and other characters, like \n, \b... Thanks to Coldspeed, I now have a function that sort of does the trick:

def back2forwardSlash(backSlash_string):    
    return backSlash_string.replace('\\', '/')

What's still unsatisfactory is that I have to call the function with the r before the string to read it as raw: fileNamePath = back2forwardSlash(r'C:\Users\Dropbox\netCFD4\b30.137.nc') This prevents passing a variable into the function, instead of pasting in the string. Or at least, I don't think I have a solution to that.

cs95
  • 379,657
  • 97
  • 704
  • 746
Pauli
  • 170
  • 3
  • 9

1 Answers1

1

The pythonic way of doing this would be using string.replace.

def foo(string):
    return string.replace('\\', '/')

Furthermore, the reason for your error is that a backslash can be taken as the start of an escape sequence, which is a group of characters that are interpreted differently from their representation. This means that the sequence \b is not two separate characters, but a single character \b, or \x08. So, you'll want to pass a raw string to your function:

print(foo(r'C:\Users\Dropbox\netCFD4\b30.137.nc'))

A raw string will treat the backslashes literally. The alternative would be to escape all your backslashes.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • Thanks COLDSPEED. The replace method does it pretty well, but the problem is actually solved only by calling the function with the `r` before the argument string, as you have suggested. This is only partially satisfactory, as I cannot pass the function with a variable, but always have to manually paste the string after the `r`, to get it raw. At least, I don't think I have a solution. – Pauli Sep 19 '17 at 09:00
  • @Pauli If your strings are coming in like this, there is a problem with the source. Also, no real way to make variables raw strings... – cs95 Sep 19 '17 at 09:07