为什么在Python中“\x”无效?

2024-06-08 18:03:10 发布

您现在位置: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”有什么特别之处?为什么它的处理方式与其他非转义字符不同?


Tags: 字符串脚本return字符tab意义vertical斜杠
3条回答

有一个表列出了所有转义代码及其在documentation中的含义。

Escape Sequence    Meaning                        Notes
\xhh               Character with hex value hh    (4,5)

Notes:

4. Unlike in Standard C, exactly two hex digits are required.
5. In a string literal, hexadecimal and octal escapes denote the byte with the given value; it is not necessary that the byte encodes a character in the source character set. In a Unicode literal, these escapes denote a Unicode character with the given value.

\xhh用于表示hex escape characters

x用于在字符串中定义(一个字节)十六进制文本,例如:

'\x61'

将计算为“a”,因为61是十六进制值97,它在ASCII中表示a

相关问题 更多 >