在 Python 中用正斜杠替换反斜杠
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4119166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace Backslashes with Forward Slashes in Python
提问by TartanLlama
I'm writing a cross platform file explorer in python. I am trying to convert any backslashes in a path into forward slashes in order to deal with all paths in one format.
我正在用 python 编写一个跨平台的文件浏览器。我试图将路径中的任何反斜杠转换为正斜杠,以便以一种格式处理所有路径。
I've tried not only using string.replace(str, '\\', '/'), but also creating a method manually to search through the string and replace the instances, and both do not work properly, as a path name such as:
我不仅尝试使用 string.replace(str, '\\', '/'),还尝试手动创建一个方法来搜索字符串并替换实例,但两者都无法正常工作,作为路径名如:
\dir\anotherdir\foodir\more
changes to:
更改为:
/dir/anotherdir\x0oodir/more
I am assuming that this has something to do with how Python represents escape characters or something of the sort. How do I prevent this happening?
我假设这与 Python 如何表示转义字符或类似的东西有关。我如何防止这种情况发生?
采纳答案by Bj?rn Pollex
回答by Tomasz Zieliński
Doesn't this work:
这不工作:
>>> s = 'a\b'
>>> s
'a\b'
>>> print s
a\b
>>> s.replace('\','/')
'a/b'
?
?
EDIT:
编辑:
Of course this is a string-based solution, and using os.pathis wiser if you're dealing with filesystem paths.
当然,这是一个基于字符串的解决方案,如果您正在处理文件系统路径,则使用os.path 更为明智。
回答by Stefano M
Elaborating this answer, with pathlibyou can use the as_posixmethod:
详细说明这个答案,使用pathlib您可以使用as_posix方法:
>>> import pathlib
>>> p = pathlib.PureWindowsPath(r'\dir\anotherdir\foodir\more')
>>> print(p)
\dir\anotherdir\foodir\more
>>> print(p.as_posix())
/dir/anotherdir/foodir/more
>>> str(p)
'\dir\anotherdir\foodir\more'
>>> str(p.as_posix())
'/dir/anotherdir/foodir/more'

