python - 为什么 Python 的原始字符串文字不能以单个反斜杠结尾?

从技术上讲,任何奇数个反斜杠,如 the documentation 中所述.

>>> r'\'
  File "<stdin>", line 1
    r'\'
       ^
SyntaxError: EOL while scanning string literal
>>> r'\\'
'\\\\'
>>> r'\\\'
  File "<stdin>", line 1
    r'\\\'
         ^
SyntaxError: EOL while scanning string literal

似乎解析器可以将原始字符串中的反斜杠视为常规字符(这不就是原始字符串的全部内容吗?),但我可能遗漏了一些明显的东西。

最佳答案

关于 python 的原始字符串的全部误解是大多数人认为反斜杠(在原始字符串中)只是一个常规字符。它不是。理解的关键是这个python的教程序列:

When an 'r' or 'R' prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string

所以反斜杠后面的任何字符都是原始字符串的一部分。一旦解析器输入一个原始字符串(非 Unicode 字符串)并遇到一个反斜杠,它就知道有 2 个字符(一个反斜杠和一个字符跟随它)。

这边:

r'abc\d' comprises a, b, c, \, d

r'abc\'d' comprises a, b, c, \, ', d

r'abc\'' comprises a, b, c, \, '

和:

r'abc\' comprises a, b, c, \, ' but there is no terminating quote now.

最后一个案例表明,根据文档,现在解析器找不到结束引号,因为您在上面看到的最后一个引号是字符串的一部分,即反斜杠不能在此处最后,因为它会“吞噬”字符串结束字符。

https://stackoverflow.com/questions/647769/

相关文章:

python - 解析 .py 文件,读取 AST,修改它,然后写回修改后的源代码

regexp)": what d">python - 命名正则表达式组 "(?Pregexp)": what d

linux - 命令行参数中的 "-"(破折号)有什么魔力?

linux - 如何反汇编原始 16 位 x86 机器代码?

linux - 即使在安装 npm install -g gulp 后也找不到本地 gulp 安装

python - 重新加载模块给出 NameError : name 'reload' is not

python - 字符串和字节字符串有什么区别?

bash - 试图在 Bash 的变量中嵌入换行符

python - APT 命令行界面,类似于是/否输入?

linux - 如何在shell中处理10多个参数