python - Telnetlib、字节串和 "invalid escape sequence"

标签 python regex string expect telnetlib

我正在使用telnetlib.expect()显然,与以字节串响应的设备进行交互。除非我在传递给 expect() 的正则表达式中使用字节串(预编译或文字),会生成异常:TypeError: cannot use a string pattern on a bytes-like object 。然而,pycodestyle提示这是 W605 invalid escape sequence '\d' ,进一步阅读让我觉得这将来会成为 Python 语法错误。

总结:

telnetlib.expect([b'\d']) # OK, but W065
telnetlib.expect(['\d'] # TypeError
telnetlib.expect([r'\d'] # TypeError

有办法解决这个问题,还是 pycodestyle 根本就是错误的?

(顺便说一句,除了抑制所有警告之外,似乎无法抑制 pycodestyle 中的 W065。)

最佳答案

字节字符串文字使用 \ 作为转义字符,就像字符串文字一样。与它们类似,您必须使用原始字节字符串文字 rb'\d' 或使用双反斜杠 b'\\d'

来自https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals

In plain English: Both types of literals can be enclosed in matching single quotes (') or double quotes ("). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple-quoted strings). The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.

关于python - Telnetlib、字节串和 "invalid escape sequence",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53223306/

相关文章:

python - Scrapy跨多个表单请求页面存储项目?元? Python

Java 正则表达式 : find a match only at the beginnings of words

java - 使用替代逗号 (,) 拆分字符串

Python:消除库代码中的堆栈跟踪?

python - Python 2.7.1 的 re 模块中 re.split 函数和 re.DOTALL 标志的错误

python - django 从主模板中的外部应用程序获取上下文

python:使用正则表达式将文档字符串捕获为精确匹配

regex - 检查正则表达式子模式是否不包含先前的子模式?

jquery - 如何在url中传递带#的字符串?

javascript - Postman 测试检查部分对象值