为什么是'\x'在Python中无效?
我正在尝试使用“\”字符,使用“\a\b\c...”只是为了自己枚举Python将哪些字符解释为控制字符以及解释为什么。这是我发现的:
\a - BELL
\b - BACKSPACE
\f - FORMFEED
\n - LINEFEED
\r - RETURN
\t - TAB
\v - VERTICAL TAB
我尝试过的大多数其他字符,'\g','\s'等只是计算为反斜杠和给定字符的2个字符的字符串。我知道这是故意的,对我来说是有道理的。
但'\x'是一个问题。当我的脚本到达此源代码行时:
val = "\x"
我得到:
ValueError: invalid \x escape
'\x' 有什么特别之处?为什么它的处理方式与其他非转义字符不同?
I was experimenting with '\' characters, using '\a\b\c...' just to enumerate for myself which characters Python interprets as control characters, and to what. Here's what I found:
\a - BELL
\b - BACKSPACE
\f - FORMFEED
\n - LINEFEED
\r - RETURN
\t - TAB
\v - VERTICAL TAB
Most of the other characters I tried, '\g', '\s', etc. just evaluate to the 2-character string of a backslash and the given character. I understand this is intentional, and makes sense to me.
But '\x' is a problem. When my script reaches this source line:
val = "\x"
I get:
ValueError: invalid \x escape
What is so special about '\x'? Why is it treated differently from the other non-escaped characters?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
文档中有一个表格列出了所有转义码及其含义。
There is a table listing all the escape codes and their meanings in the documentation.
\xhh
用于表示十六进制转义字符 。\xhh
is used to represent hex escape characters.x 用于定义字符串中的(一个字节)十六进制文字,例如:
将计算为 'a',因为 61 是 97 的十六进制值,在 ASCII 中表示 a
x is used to define (one byte) hexadecimal literals in strings, for example:
will evaluate to 'a', because 61 is the hexadecimal value of 97, which represents a in ASCII
\x 缺少要匹配的十六进制字符:\xnn -> \x1B
\x is missing the hex character you want to match against: \xnn -> \x1B
您没有给出完整的转义序列:
来自: http:// /www.gnu.org/software/gawk/manual/html_node/Escape-Sequences.html
You're not giving the full escape sequence:
From: http://www.gnu.org/software/gawk/manual/html_node/Escape-Sequences.html