我想了解python3的bytes
和bytearray
课程.我看过关于它们的文档,但没有全面描述它们的差异以及它们如何与string
个对象交互.
我想了解python3的bytes
和bytearray
课程.我看过关于它们的文档,但没有全面描述它们的差异以及它们如何与string
个对象交互.
python3的bytes
和bytearray
类都包含字节数组,每个字节的值都在0到255之间.主要区别在于bytes
对象是immutable,这意味着一旦创建,就不能修改其元素.相比之下,bytearray
对象允许您修改其元素.
bytes
和bytearay
都提供对字符串进行编码和解码的功能.
bytes
and encoding strings字节对象可以用几种不同的方式构造:
>>> bytes(5)
b'\x00\x00\x00\x00\x00'
>>> bytes([97, 98, 99])
b'abc'
>>> b'abc'
b'abc'
>>> bytes('abc')
TypeError: string argument without an encoding
>>> bytes('abc', 'utf-8')
b'abc'
>>> 'abc'.encode('utf-8')
b'abc'
>>> 'abc'.encode('utf-16')
b'\xff\xfea\x00b\x00c\x00'
>>> 'abc'.encode('utf-16-le')
b'a\x00b\x00c\x00'
请注意最后两个选项之间的区别:"utf-16"指定了通用的utf-16
因为字节对象是不可变的,试图更改其中一个元素
>>> a = bytes('abc', 'utf-8')
>>> a
b'abc'
>>> a[1] = 102
TypeError: 'bytes' object does not support item assignment
与bytes
类似,字节数组可以通过多种方式构造:
>>> bytearray(5)
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00')
>>>bytearray([1, 2, 3])
bytearray(b'\x01\x02\x03')
>>> bytearray('abc')
TypeError: string argument without an encoding
>>> bytearray('abc', 'utf-8')
bytearray(b'abc')
>>> bytearray('abc', 'utf-16')
bytearray(b'\xff\xfea\x00b\x00c\x00')
>>> bytearray('abc', 'utf-16-le')
bytearray(b'a\x00b\x00c\x00')
因为字节数组是mutable,所以可以修改其元素:
>>> a = bytearray('abc', 'utf-8')
>>> a
bytearray(b'abc')
>>> a[1]=114
>>> a
bytearray(b'arc')
bytes
和bytearray
个对象可与+运算符连接:
>>> a = bytes(3)
>>> a
b'\x00\x00\x00'
>>> b = bytearray(4)
>>> b
bytearray(b'\x00\x00\x00\x00')
>>> a+b
b'\x00\x00\x00\x00\x00\x00\x00'
>>> b+a
bytearray(b'\x00\x00\x00\x00\x00\x00\x00')
请注意,链接结果采用第一个参数的类型,因此a+b
生成bytes
对象,b+a
生成bytearray
.
字节和字节数组对象可以使用decode
函数转换为字符串.该函数假定您提供的解码类型与编码类型相同.例如:
>>> a = bytes('abc', 'utf-8')
>>> a
b'abc'
>>> a.decode('utf-8')
'abc'
>>> b = bytearray('abc', 'utf-16-le')
>>> b
bytearray(b'a\x00b\x00c\x00')
>>> b.decode('utf-16-le')
'abc'