【问题标题】:Replace "\\" with "\" in Python 3.x在 Python 3.x 中将“\\”替换为“\”
【发布时间】:2021-05-15 10:49:42
【问题描述】:

我有一个包含 Windows 文件路径的字符串:

import os
dir = os.getcwd()
# bogus name
'C:\\my\\folder'

如果我在 Windows 资源管理器或其他程序中复制并粘贴 dir,则会收到错误消息,文件名无效。

我尝试了question 中的解决方案,但都没有奏效。 我得到的最接近的是:

dir.replace('\\', '/')
'C:/my/folder'

现在它适用于某些 Windows 程序,但不适用于其他程序,所以我只想将 '\\' 替换为 '\'

【问题讨论】:

  • 内容从何而来?它是否也通过 print() 输出 '\\' 形式?

标签: python-3.x string windows path


【解决方案1】:

如果您在 python shell 中并且刚刚评估了目录,那么print(dir) 就足够了。

否则你会想要print(dir.replace('\\\\', '\\')),这似乎是 os.getcwd() 的一个非常奇怪的输出

请记住,“\”是一个转义字符,因此需要自行转义。

以下是 Python shell 的示例:

>>> a = 'c:\\foo\\bar'
>>> a
'c:\\foo\\bar'
>>> print(a)
c:\foo\bar

【讨论】:

  • (我运行的是Linux,所以无法用os.getcwd()快速测试)
猜你喜欢
  • 1970-01-01
  • 2013-03-14
  • 1970-01-01
  • 1970-01-01
  • 2020-07-18
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多