在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:21:36  来源:igfitidea点击:

Replace Backslashes with Forward Slashes in Python

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

You should use os.pathfor this kind of stuff. In Python 3, you can also use pathlibto represent paths in a portable manner, so you don't have to worry about things like slashes anymore.

你应该os.path用于这种东西。在 Python 3 中,您还可以使用pathlib可移植的方式来表示路径,因此您不必再担心斜线之类的问题。

回答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'