
5.6 字节序列
字节序列(bytes和bytearray)是由8位字节数据组成的序列数据类型,即0≤x<256的整数序列。Python内置的字节序列数据类型包括bytes(不可变对象)、bytearray(可变对象)和memoryview。
5.6.1 bytes常量
使用字母b加单引号或双引号括起来的内容是bytes常量。Python解释器自动创建bytes型对象实例。bytes常量与字符串的定义方式类似。
(1)单引号(b' '):包含在单引号中的字符串,其中可以包含双引号。
(2)双引号(b" "):包含在双引号中的字符串,其中可以包含单引号。
(3)三单引号(b''' '''):包含在三单引号中的字符串,可以跨行。
(4)三双引号(b""" """):包含在三双引号中的字符串,可以跨行。
注意:在引号中只能包含ASCII码字符,否则将导致SyntaxError。例如:

【例5.18】 bytes常量示例。

5.6.2 创建bytes对象
创建bytes类型的对象实例的基本形式如下。

如果iterable中包含非0≤x<256的整数,将导致ValueError。
【例5.19】 创建bytes对象示例。

5.6.3 创建bytearray对象
创建bytearray类型的对象实例的基本形式如下。

如果iterable中包含非0≤x<256的整数,将导致ValueError。
【例5.20】 创建bytearray对象示例。

5.6.4 bytes和bytearray的序列操作
bytes和bytearray支持序列的基本操作,包括索引访问、切片操作、连接操作、重复操作、成员关系操作、比较运算操作,以及求序列的长度、最大值、最小值等。
bytes和bytearray一般基于ASCII字符串,故bytes和bytearray基本上支持str对象的类似方法,但不支持str.encode()(把字符串转换为bytes对象)、str.format()/str.format_map()(字符串格式化)、str.isidentifier()/str.isnumeric()/str.isdecimal()/str.isprintable()(这些判断无意义)。
注意:bytes和bytearray的方法不接受字符串参数,只接受bytes和bytearray参数,否则将导致TypeError。
【例5.21】 字节的序列操作示例。

5.6.5 字节编码和解码
字符串可以通过str.encode()方法编码为字节码,通过bytes和bytearray的decode()方法解码为字符串。
【例5.22】 字节编码和解码示例。
