Python 3.6.7
不管输入的路径是 \ 还是 /,也不管当前系统需要什么样的,都能正确转换。
1. 逻辑比较清晰
import os
def convert_path(path: str) -> str:
seps = r'\/'
sep_other = seps.replace(os.sep, '')
return path.replace(sep_other, os.sep) if sep_other in path else path
print(convert_path(r'a\b\c\d\e'))
print(convert_path(r'a/b/c/d/e'))
print(convert_path(r'a\b/c\d/e'))
# a/b/c/d/e
# a/b/c/d/e
# a/b/c/d/e
# 我的是Mac,所以 os.sep 是 /
2. 其实,判断 in 也是需要遍历,replace 又要遍历,还不如不判断 in 直接使用replace效率更高呢。
import os
def convert_path(path: str) -> str:
return path.replace(r'\/'.replace(os.sep, ''), os.sep)