在 Python 3.x 中将“\\”替换为“\”
Replace "\\" with "\" in Python 3.x
我有一个字符串,其中包含 Windows 的文件路径:
import os
dir = os.getcwd()
# bogus name
'C:\my\folder'
如果我在 Windows 资源管理器或其他程序中复制并粘贴 dir
,我会收到错误消息,文件名无效。
我尝试了此 question 中的解决方案,但 none 有效。
我得到的最接近的是:
dir.replace('\', '/')
'C:/my/folder'
现在它适用于某些 windows 程序但不适用于其他程序,所以我只想将 '\'
替换为 '\'
如果您在 python shell 中并且刚刚评估了目录,print(dir)
.
就足够了
否则你会想做 print(dir.replace('\\', '\'))
,这似乎是 os.getcwd()
的一个非常奇怪的输出
请记住,“\”是一个转义字符,因此需要对其本身进行转义。
这是来自 Python shell 的示例:
>>> a = 'c:\foo\bar'
>>> a
'c:\foo\bar'
>>> print(a)
c:\foo\bar
我有一个字符串,其中包含 Windows 的文件路径:
import os
dir = os.getcwd()
# bogus name
'C:\my\folder'
如果我在 Windows 资源管理器或其他程序中复制并粘贴 dir
,我会收到错误消息,文件名无效。
我尝试了此 question 中的解决方案,但 none 有效。 我得到的最接近的是:
dir.replace('\', '/')
'C:/my/folder'
现在它适用于某些 windows 程序但不适用于其他程序,所以我只想将 '\'
替换为 '\'
如果您在 python shell 中并且刚刚评估了目录,print(dir)
.
否则你会想做 print(dir.replace('\\', '\'))
,这似乎是 os.getcwd()
请记住,“\”是一个转义字符,因此需要对其本身进行转义。
这是来自 Python shell 的示例:
>>> a = 'c:\foo\bar'
>>> a
'c:\foo\bar'
>>> print(a)
c:\foo\bar