Python 内建函数 - bytearray([source[, encoding[, errors]]])

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'')

拓展阅读

bytes()
str.encode()

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值