如何在 python3 中将反斜杠字符串转换为正斜杠字符串?

How to convert backslash string to forward slash string in python3?

我在 ubuntu 机器上使用 python3。 我有一个字符串变量,它包含一个带反斜杠的路径,我需要将它转换为正斜杠字符串。所以我尝试了

import pathlib
s = '\dir\wnotherdir\joodir\more'
x = repr(s)
p = pathlib.PureWindowsPath(x)
print(p.as_posix())

这将正确打印为

/dir/wnotherdir/joodir/more

但是对于不同的其他字符串路径,它的行为很奇怪。例如,对于字符串,

'\dir\aotherdir\oodir\more'

它正确地替换了反斜杠,但值是错误的,因为原始字符串中的字符 'a'

/dir/x07otherdir/oodir/more

这种行为的原因是什么?

这与路径本身无关。这里的问题是 \a 被解释为 ASCII BELL. As a rule of thumb whenever you want to disable the special interpretation of escaped string literals you should use raw 字符串:

>>> import pathlib
>>> r = r'\dir\aotherdir\oodir\more'
>>> pathlib.PureWindowsPath(r)
PureWindowsPath('/dir/aotherdir/oodir/more')
>>>