views:

331

answers:

3

Hello, I'm making a program that asks for a path, and Windows' paths contain backslashes, which can be interpreted as an escape sequence by python if the letter right next is the wrong one. I tried string.replace() but it doesn't work as these backslashes get transformed into escape sequences before having the replace function executed.

Is there a way to remove them and maybe make them / instead of \?

+6  A: 

No, the backslash is not interpreted as an escape sequence except in Python source code. Unless you're eval()ing the path, which would be Wrong, I'm not sure why you'd have a problem.

Jonathan Feinberg
>>> a = "C:\Program Files\a\n\b">>> a'C:\\Program Files\x07\n\x08'I did this in IDLE, they do get interpreted
Gabriele Cirulli
Yep. That's Python source code.
Jonathan Feinberg
+3  A: 

If you are asking for the user for input, then a \ will go into a string as a \ correctly. Only if you then eval the user's string in some way will the backslash count as an escape char. You really only need to worry about escaping when you are writing strings within the code.

Zak
thanks, the problem was me not understanding this and thinking it would be transformed in an escape sequence every time in every case
Gabriele Cirulli
Use `os.path` to manipulate these and you'll never have to worry.
S.Lott
@terabytest: When you have a thought like that, try testing it in the interactive interpreter. Feedback time is much faster than SO!
John Machin
+3  A: 

Use double \

str = 'c:\\dir\\file.txt'

print str.replace('\\','/')
print str

here us the output

c:/dir/file.txt
c:\dir\file.txt
Elalfer