Manual
Return a new array of bytes. The bytearray class is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Bytearray Operations.
The optional source parameter can be used to initialize the array in a few different ways:
- If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().
- If it is an integer, the array will have that size and will be initialized with null bytes.
- If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.
- If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.
Without an argument, an array of size 0 is created.
直译
返回一个新的字节数组。bytearray类是一个值域为0 <= x < 256的可变整数序列。它具有大多数可变序列的常用方法,这将在可变序列类型中进行描述,其大多方法与bytes类型相同,详细参考bytes和bytesarray操作。
可选source参数可通过几种途径来初始化数组:
- 如果是字符串,必须添加encoding(和可选error项)参数,然后bytearray() 通过利用str.encode()将字符串转化为字节
- 如果是整数,数组获得其大小,并用空字节进行初始化
- 如果是迭代,它必须是一个值域为0 <= x < 256的整数迭代,用于初始化数组的内容
无参数时,则创建一个大小为0的数组。
实例
字符串
>>> bytearray('CSDN', 'utf-8')
bytearray(b'CSDN')
整数
>>> bytearray(17)
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
迭代
>>> bytearray(range(10))
bytearray(b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t')
>>> bytearray(i for i in range(2, 21) if i % 2 == 0)
bytearray(b'\x02\x04\x06\x08\n\x0c\x0e\x10\x12\x14')
无参数
>>> bytearray()
bytearray(b'')