Python 3字节的奇怪表示法 [英] Strange notation for Python 3 bytes
问题描述
有人可以确定这些个字节
的表示法是什么吗?乍一看,我倾向于认为是十六进制,但我不认识 xf1Y
和 e1fl
之类的东西是:
Can someone identify what this notation for these bytes
is? At first glance, I tend to think "hexadecimal", but I don't recognize what things like xf1Y
and e1fl
are:
b'vy\xe9\xb5\xa2\xba\xf1Y\xe8\xe1fl\x1d\x87\xacC'
当我使用<$ c进行编码时,我会得到这个$ c> some_text.encode('utf-8')。
我正在尝试获取可传递给加密方法的字节,使用Python 2的字节字符串。
I am trying to get bytes that I can pass to cryptography methods that worked with Python 2's byte strings.
推荐答案
您是对的-这是一个十六进制表示法。
You're right – it's a hexadecimal notation.
在字节文字中,不能由可打印的ASCII字符表示的任何字节(或标准转义符 \n
, \t
或 \r
)表示为 \xNN
,其中NN是字节的2位十六进制表示形式。
In a bytes literal, any byte which can't be represented by a printable ASCII character (or one of the standard escapes \n
, \t
or \r
) is represented as \xNN
, where NN is the 2-digit hexadecimal representation of the byte.
让您感到困惑的是,您误会了例如 \xf1Y
表示单个转义序列,实际上它表示两个单独的字节:
What's confusing you is that you're mistaking e.g. \xf1Y
for a single escape sequence, when in fact it represents two separate bytes:
>>> len(b'\xf1Y')
2
>>> [bytes([b]) for b in b'\xf1Y']
[b'\xf1', b'Y']
如果迭代一个字节对象,您将获得字节的整数值:
If you iterate over a bytes object, you'll get the integer values of the bytes back:
>>> list(b'vy\xe9\xb5\xa2\xba\xf1Y\xe8\xe1fl\x1d\x87\xacC')
[118, 121, 233, 181, 162, 186, 241, 89, 232, 225, 102, 108, 29, 135, 172, 67]
>>> bytes([118])
b'v'
>>> bytes([121])
b'y'
>>> bytes([233])
b'\xe9'
的文档href = https://docs.python.org/3.5/reference/lexical_analysis.html#index-18 rel = noreferrer> Python字符串和字节对象中的转义序列有关转义的更多信息Python可以理解的序列(尽管上面的序列是它用来表示字节对象的唯一序列)。
The documentation for escape sequences in Python string and bytes objects has a little more information on escape sequences Python understands (although those above are the only ones it uses to represent bytes objects).
这篇关于Python 3字节的奇怪表示法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!