class bytearray([source[, encoding[, errors]]])
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:
def __init__(self, source=None, encoding=None, errors=‘strict‘): # known special case of bytearray.__init__
"""
bytearray(iterable_of_ints) -> bytearray
bytearray(string, encoding[, errors]) -> bytearray
bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer
bytearray(int) -> bytes array of size given by the parameter initialized with null bytes
bytearray() -> empty bytes array
Construct a mutable bytearray object from:
- an iterable yielding integers in range(256)
- a text string encoded using the specified encoding
- a bytes or a buffer object
- any object implementing the buffer API.
- an integer
# (copied from class doc)
"""
pass
返回一个新的字节数组。
bytearray类是range 0 < = x < 256的一个可变序列。
它有大多数可变序列的常用方法,在可变序列类型中描述,以及大多数字节类型的方法,参见字节和Bytearray操作。
可选的源参数可以用几种不同的方式来初始化数组:
如果没有参数,则创建一个大小为0的数组。
#!/usr/bin/python3
b = bytearray()
print(b)<br>print(len(b))
结果:
bytearray(b‘‘)
0
b = bytearray(‘中文‘)
Traceback (most recent call last):
File "D:/py/day001/day1/test.py", line 3, in <module>
b = bytearray(‘中文‘)
TypeError: string argument without an encoding
encoding参数也必须提供,函数将字符串使用str.encode方法转换成字节数组
b = bytearray(‘中文‘, ‘utf-8‘)
print(b)
print(len(b))
结果:
bytearray(b‘\xe4\xb8\xad\xe6\x96\x87‘)
6
#!/usr/bin/python3
b = bytearray(5)
print(b)
print(len(b))
执行结果:
bytearray(b‘\x00\x00\x00\x00\x00‘)
5
#!/usr/bin/python3
b = bytearray([1,2,3,4,5])
print(b)
print(len(b))
执行结果:
bytearray(b‘\x01\x02\x03\x04\x05‘)
5
#!/usr/bin/python3
b = bytearray([1,2,3,4,5,256])
print(b)
print(len(b))
执行结果:
Traceback (most recent call last):
File "D:/py/day001/day1/test.py", line 3, in <module>
b = bytearray([1,2,3,4,5,256])
ValueError: byte must be in range(0, 256)
Python内置函数—bytearray
我觉得这篇总结得非常好,为了防止下次要用的时候找不着,因此转载。
原文:https://www.cnblogs.com/cyx-b/p/13456333.html