Python3.6内置函数(8)——bytes()

浏览: 1808

英文文档

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

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

图片.png

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

0 个评论

要回复文章请先登录注册