首页 > 解决方案 > 交互式 python 中的意外行为

问题描述

>>> r'\'

SyntaxError:扫描字符串文字时 EOL

我期望'\\'作为输出。

标签: pythonpython-3.xstringinteractivepython-3.8

解决方案


根据 Python 文档https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals

shortstring     ::=  "'" shortstringitem* "'" | '"' shortstringitem* '"'
shortstringitem ::=  shortstringchar | stringescapeseq
shortstringchar ::=  <any source character except "\" or newline or the quote>
stringescapeseq ::=  "\" <any source character>

查看词法元素的定义shortstringchar,很明显即使在原始字符串中r''r""单个反斜杠后跟某些内容也将被视为字符串内容的一部分,因为 LL(1) 分析器下降到stringescapeseq而不是读取“字符串结尾” " 标记,因此以下单引号不会被解析为“原始字符串结尾”。

虽然不那么直观,但词法分析器(Python 目前使用 LL(1) 解析器)就是这样设计的。

如果您真的想要一个只有一个反斜杠的字符串,请使用'\\'or "\\"(无r前缀)。


推荐阅读