Python将反斜杠转换为正斜杠 [英] Python Convert Back Slashes to forward slashes
问题描述
我在 python 中工作,我需要转换这个:
I am working in python and I need to convert this:
C:\folderA\folderB 到 C:/folderA/folderB
C:\folderA\folderB to C:/folderA/folderB
我有三种方法:
dir = s.replace('\\','/')
dir = os.path.normpath(s)
dir = os.path.normcase(s)
在每个场景中的输出都是
In each scenario the output has been
C:folderAfolderB
C:folderAfolderB
我不确定我做错了什么,有什么建议吗?
I'm not sure what I am doing wrong, any suggestions?
推荐答案
您的具体问题是 replace
参数的顺序和转义,应该是
Your specific problem is the order and escaping of your replace
arguments, should be
s.replace('\\', '/')
然后是:
posixpath.join(*s.split('\\'))
在 *nix 平台上相当于:
Which on a *nix platform is equivalent to:
os.path.join(*s.split('\\'))
但是不要在 Windows 上依赖它,因为它更喜欢特定于平台的分隔符.还有:
But don't rely on that on Windows because it will prefer the platform-specific separator. Also:
请注意,在 Windows 上,因为每个目录都有一个当前目录drive, os.path.join("c:", "foo") 表示相对于驱动器 C: (c:foo) 上的当前目录,而不是 c:\foo.
Note that on Windows, since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.
这篇关于Python将反斜杠转换为正斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!