Python3.6内置函数(7)——bytearray()

浏览: 2467

英文文档

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.

bytearray()

1、返回值为一个新的字节数组

2、当3个参数都不传的时候,返回长度为0的字节数组

>>> b = bytearray()

>>> b

bytearray(b'')

>>> len(b)

0

 

3、当source参数为字符串时,encoding参数也必须提供,函数将字符串使用str.encode方法转换成字节数组

>>> bytearray('中文字符')

Traceback (most recent call last):

 File "<pyshell#54>", line 1, in <module>

   bytearray('中文字符')

TypeError: string argument without anencoding

>>> bytearray('中文字符', 'utf8')

bytearray(b'\xe4\xb8\xad\xe6\x96\x87\xe5\xad\x97\xe7\xac\xa6')

>>> bytearray('中文字符', 'utf-8')

bytearray(b'\xe4\xb8\xad\xe6\x96\x87\xe5\xad\x97\xe7\xac\xa6')

 

4、当source参数为整数时,返回这个整数所指定长度的空字节数组

>>> bytearray(9)

bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00')

>>> bytearray(-9) #整数需大于0,用来做数组长度

Traceback (most recent call last):

 File "<pyshell#58>", line 1, in <module>

   bytearray(-9)

ValueError: negative count

 

5、当source参数为实现了buffer接口的object对象时,那么将使用只读方式将字节读取到字节数组后返回

6、当source参数是一个可迭代对象,那么这个迭代对象的元素都必须符合0 <= x < 256,以便可以初始化到数组里

>>> bytearray([1,2,3])

bytearray(b'\x01\x02\x03')

>>> bytearray([256,2,3]) #不在0-255范围内报错

Traceback (most recent call last):

 File "<pyshell#60>", line 1, in <module>

   bytearray([256,2,3]) #不在0-255范围内报错

ValueError: byte must be in range(0, 256)

小结

希望通过上面的操作能帮助大家。如果你有什么好的意见,建议,或者有不同的看法,我都希望你留言和我们进行交流、讨论。

欢迎关注微信公众号,访问更多精彩:AiryData

如需转载,请联系授权,谢谢合作。

图片.png

推荐 0
本文由 Airy 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册