Python內(nèi)置函數(shù)(7)——bytearray

英文文檔:

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:

  • 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.

說(shuō)明:

1.返回值為一個(gè)新的字節(jié)數(shù)組

2.當(dāng)3個(gè)參數(shù)都不傳的時(shí)候,返回長(zhǎng)度為0的字節(jié)數(shù)組

>>> b = bytearray()
>>> b
bytearray(b'')
>>> len(b)
0

3.當(dāng)source參數(shù)為字符串時(shí),encoding參數(shù)也必須提供,函數(shù)將字符串使用str.encode方法轉(zhuǎn)換成字節(jié)數(shù)組

>>> bytearray('中文')
Traceback (most recent call last): 
  File "<pyshell#48>", line 1, in <module> 
    bytearray('中文')
TypeError: string argument without an encoding
>>> bytearray('中文','utf-8')
bytearray(b'\xe4\xb8\xad\xe6\x96\x87')

4.當(dāng)source參數(shù)為整數(shù)時(shí),返回這個(gè)整數(shù)所指定長(zhǎng)度的空字節(jié)數(shù)組

>>> bytearray(2)
bytearray(b'\x00\x00')
>>> bytearray(-2) #整數(shù)需大于0,使用來(lái)做數(shù)組長(zhǎng)度的
Traceback (most recent call last): 
  File "<pyshell#51>", line 1, in <module> 
    bytearray(-2)
ValueError: negative count

5.當(dāng)source參數(shù)為實(shí)現(xiàn)了buffer接口的object對(duì)象時(shí),那么將使用只讀方式將字節(jié)讀取到字節(jié)數(shù)組后返回

6.當(dāng)source參數(shù)是一個(gè)可迭代對(duì)象,那么這個(gè)迭代對(duì)象的元素都必須符合0 <= x < 256,以便可以初始化到數(shù)組里

>>> bytearray([1,2,3])
bytearray(b'\x01\x02\x03')
>>> bytearray([256,2,3]) #不在0-255范圍內(nèi)報(bào)錯(cuò)
Traceback (most recent call last): 
  File "<pyshell#53>", line 1, in <module> 
    bytearray([256,2,3])
ValueError: byte must be in range(0, 256)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容