问题描述
我正在试验'\'字符,使用'\ a \ b \ c ...'只是为了自己枚举Python解释为控制字符的字符以及什么.这是我发现的:
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
我尝试过的大多数其他字符,例如'\ g','\ s'等,仅求反斜杠和给定字符的2个字符的字符串.我知道这是故意的,对我来说很有意义.
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.
但是'\ x'是一个问题.当我的脚本到达此源代码行时:
But '\x' is a problem. When my script reaches this source line:
val = "\x"
我得到:
ValueError: invalid \x escape
'\ x'有什么特别之处?为什么与其他非转义字符区别对待?
What is so special about '\x'? Why is it treated differently from the other non-escaped characters?
推荐答案
在文档.
Escape Sequence Meaning Notes
\xhh Character with hex value hh (4,5)
4.与标准C中的不同,仅需要两个十六进制数字.
5.在字符串文字中,十六进制和八进制转义符表示字节 具有给定值;字节不必编码一个字符 在源字符集中.在Unicode文字中,这些转义符表示一个 具有给定值的Unicode字符.
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.
这篇关于为什么'\ x'在Python中无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!