gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:13:24 25 4
gpt4 key购买 nike

显然,我正在使用 telnetlib.expect() 与以字节串响应的设备交互。除非我在传递给 expect() 的正则表达式中使用字节字符串(预编译或文字),否则会生成异常:TypeError: cannot use a string pattern on a bytes-like object。然而,pycodestyle 提示这是 W605 invalid escape sequence '\d',进一步阅读让我认为这将成为 future 的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com