英文文档
class bytes([source[, encoding[, errors]]])
Return a new “bytes” object, which is animmutable sequence of integers in the range 0 <= x < 256. bytes is animmutable version of bytearray – it has the same non-mutating methods and thesame indexing and slicing behavior.
Accordingly, constructor arguments areinterpreted as for bytearray().
bytes()
bytes([source[, encoding[, errors]]])
1、返回值为一个新的不可修改字节数组,每个数字元素都必须在0 – 255范围内,是bytearray函数的具有相同的行为,差别仅仅是返回的字节数组不可修改。
2、当3个参数都不传的时候,返回长度为0的字节数组
>>> b = bytes()
>>> b
b''
>>> len(b)
0
3、当source参数为字符串时,encoding参数也必须提供,函数将字符串使用str.encode方法转换成字节数组
>>> bytes('中文字符') #需要传入编码格式
Traceback (most recent call last):
File "<pyshell#67>", line 1, in <module>
bytes('中文字符') #需要传入编码格式
TypeError: string argument without anencoding
>>> bytes('中文字符', 'utf8')
b'\xe4\xb8\xad\xe6\x96\x87\xe5\xad\x97\xe7\xac\xa6'
>>> '中文字符'.encode('utf8')
b'\xe4\xb8\xad\xe6\x96\x87\xe5\xad\x97\xe7\xac\xa6'
4、当source参数为整数时,返回这个整数所指定长度的空字节数组
>>> bytes(9)
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>> bytes(-9) #整数需大于0,用来做数组长度
Traceback (most recent call last):
File "<pyshell#71>", line 1, in <module>
bytes(-9) #整数需大于0,用来做数组长度
ValueError: negative count
5、当source参数为实现了buffer接口的object对象时,那么将使用只读方式将字节读取到字节数组后返回
6、当source参数是一个可迭代对象,那么这个迭代对象的元素都必须符合0 <= x < 256,以便可以初始化到数组里
>>> bytes([1,2,3])
b'\x01\x02\x03'
>>> bytes([256,2,3])
Traceback (most recent call last):
File "<pyshell#73>", line 1, in <module>
bytes([256,2,3])
ValueError: bytes must be in range(0, 256)
7、返回数组不可修改
>>> a = bytes(10)
>>> a
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>> a[0]
0
>>> a[1] = 1 #不可修改
Traceback (most recent call last):
File "<pyshell#77>", line 1, in <module>
a[1]= 1
TypeError: 'bytes' object does not supportitem assignment
>>>
>>> a = bytearray(10)
>>> a
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
>>> a[1] = 1 #可修改
>>> a
bytearray(b'\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00')
小结
希望通过上面的操作能帮助大家。如果你有什么好的意见,建议,或者有不同的看法,我都希望你留言和我们进行交流、讨论。
欢迎关注微信公众号,访问更多精彩:AiryData。
如需转载,请联系授权,谢谢合作。