python - 交互式 python 中的意外行为
问题描述
>>> r'\'
SyntaxError:扫描字符串文字时 EOL
我期望'\\'
作为输出。
解决方案
根据 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
前缀)。
推荐阅读
- excel - 使用 if 函数从列中提取日期(如果它存在)或另一个(如果它在 excel 中缺失)
- java - 如何制作一种从 x 和 o 中创建模式的方法?
- progressive-web-apps - 网页调用GameClient的setViewForPopups实现自动登录
- reactjs - 下一个 js 应用程序(在 docker 容器内运行)无法加载位于公共目录中的静态文件图像
- ruby-on-rails - Rails AWS 播种图像 URL 不起作用
- reactjs - RxJS 和重复事件
- android-jetpack-navigation - NavDeepLinkBuilder 上缺少 setDestination 方法
- while-loop - 如何在程序中添加计时器?
- javascript - 禁用特定幻灯片上的按钮
- python - Python Selenium 从特定 div 中查找元素