0

(For the purpose here, I'm using Python 2.7.13 on Windows.)

I was told that user input strings are automatically read as raw string literal here. However, using a simple example:

def test (filename):
  return(os.path.normpath (filename))

test('Y:\Projects\14. MOON-301\Neoantigen\normal-10NB-tumor-10TB\normal-10NB-tumor-10TB-lib.txt')
'Y:\\Projects\x0c. MOON-301\\Neoantigen\normal-10NB-tumor-10TB\normal-10NB-tumor-10TB-lib.txt'

Which acts like normpath is treating filename as a string literal rather than a raw string literal. Of course I can use eval to coerce it back into raw string literals, but is there a more elegant way to do it?

John M.
  • 9
  • 3
  • `os.path.normpath` isn't interpreting backslashes. Python string literal syntax is doing that. – user2357112 Aug 02 '17 at 17:08
  • 1
    Use a `r'raw\string'` – anthony sottile Aug 02 '17 at 17:08
  • Using a raw string is indeed the appropriate approach here, because you are using string literals – Cory Kramer Aug 02 '17 at 17:10
  • If you're in one of the rare cases where you really do need backslashes for the path - forward slashes are usually fine, even on Windows - then raw strings are a perfectly okay way to go about it. Just remember that if you need a trailing backslash, you have to provide that by concatenating a second string. – user2357112 Aug 02 '17 at 17:10

0 Answers0