【问题标题】:How to make python 3 understand double backslash? [duplicate]如何让 python 3 理解双反斜杠? [复制]
【发布时间】:2021-10-04 01:57:36
【问题描述】:

所以,正如 SO 一直建议我的那样,我不想替换双反斜杠,我希望 python 能够理解它们。

我需要将文件从 Windows 远程目录复制到我的本地计算机。

例如,shell 中的“等效”(即使不是)(带有 windows 路径):

cp \\directory\subdirectory\file ./mylocalfile

但是python甚至不理解字符串中的双反斜杠:

source = "\\dir\subdir\file"
print(source)

$ python __main__.py 
__main__.py:1: DeprecationWarning: invalid escape sequence \s
  source = "\\dir\subdir\file"
\dir\subdir
           ile

Python 是否能够理解 Windows 路径(带有双反斜杠)以执行文件复制?

【问题讨论】:

  • 使用原始字符串文字
  • 在字符串文字上使用 r 前缀。

标签: python python-3.x windows


【解决方案1】:

你也可以试试这个:

source = r"\dir\subdir\file"
print(source)
# \dir\subdir\file

您也可以通过使用此原始字符串来解决此问题。
我们在这里所做的是首先使用r"\dir\subdir\file" 转换为原始字符串。

您可以访问here了解其他信息。

原始字符串是将反斜杠 (\) 视为文字字符的原始字符串文字。例如,如果我们尝试打印一个内部带有“\n”的字符串,它将添加一个换行符。但是如果我们将其标记为原始字符串,它会简单地将“\n”打印为普通字符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-24
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 2018-06-07
    • 1970-01-01
    • 2020-02-01
    • 2017-05-18
    相关资源
    最近更新 更多