开发者

Python, removing the \'s before getting them processed

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 strin开发者_运维问答g.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 \?


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.


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.


Use double \

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

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

here us the output

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜