Python內建函數(7)——bytearray,pythonbytearray

來源:互聯網
上載者:User

Python內建函數(7)——bytearray,pythonbytearray

英文文檔:

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.

說明:

    1. 傳回值為一個新的位元組數組

    2. 當3個參數都不傳的時候,返回長度為0的位元組數組

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

 

    3. 當source參數為字串時,encoding參數也必須提供,函數將字串使用str.encode方法轉換成位元組數組

>>> 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. 當source參數為整數時,返回這個整數所指定長度的空位元組數組

>>> bytearray(2)bytearray(b'\x00\x00')>>> bytearray(-2) #整數需大於0,使用來做數組長度的Traceback (most recent call last):  File "<pyshell#51>", line 1, in <module>    bytearray(-2)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#53>", line 1, in <module>    bytearray([256,2,3])ValueError: byte must be in range(0, 256)

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.