1. 程式人生 > 實用技巧 >Python內建函式—bytearray

Python內建函式—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
    def __init__(self, source=None, encoding=None, errors='strict'): # known special case of bytearray.__init__
        """
        bytearray(iterable_of_ints) -> bytearray
        bytearray(string, encoding[, errors]) -> bytearray
        bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer
        bytearray(int) -> bytes array of size given by the parameter initialized with null bytes
        bytearray() -> empty bytes array
        
        Construct a mutable bytearray object from:
          - an iterable yielding integers in range(256)
          - a text string encoded using the specified encoding
          - a bytes or a buffer object
          - any object implementing the buffer API.
          - an integer
        # (copied from class doc)
        """
        pass

返回一個新的位元組陣列。
bytearray類是range 0 < = x < 256的一個可變序列。
它有大多數可變序列的常用方法,在可變序列型別中描述,以及大多數字節型別的方法,參見位元組和Bytearray操作。

可選的源引數可以用幾種不同的方式來初始化陣列:

  • 如果它是一個字串,那麼您還必須給出編碼(以及可選的錯誤)引數;bytearray()然後使用str.encode()將字串轉換為位元組。
  • 如果它是一個整數,那麼陣列將具有這個大小,並將用null位元組初始化。
  • 如果它是符合緩衝區介面的物件,則將使用物件的只讀緩衝區來初始化位元組陣列。
  • 如果它是可迭代的,那麼它必須是range 0 < = x < 256的整數的迭代,它被用作陣列的初始內容

如果沒有引數,則建立一個大小為0的陣列。

說明

  1. 返回值為一個新的位元組陣列
  2. 當3個引數都不傳的時候,返回長度為0的位元組陣列
#!/usr/bin/python3
 
b = bytearray()
print(b)<br>print(len(b))

結果:

bytearray(b'')
0
  1. 當source引數為字串時,encoding引數也必須提供,函式將字串使用str.encode方法轉換成位元組陣列
    b = bytearray('中文')
    結果:
Traceback (most recent call last):
  File "D:/py/day001/day1/test.py", line 3, in <module>
    b = bytearray('中文')
TypeError: string argument without an encoding

encoding引數也必須提供,函式將字串使用str.encode方法轉換成位元組陣列

b = bytearray('中文', 'utf-8')
print(b)
print(len(b))

結果:

bytearray(b'\xe4\xb8\xad\xe6\x96\x87')
6
  1. 當source引數為整數時,返回這個整數所指定長度的空位元組陣列
#!/usr/bin/python3
 
b = bytearray(5)
print(b)
print(len(b))

執行結果:

bytearray(b'\x00\x00\x00\x00\x00')
5
  1. 當source引數為實現了buffer介面的object物件時,那麼將使用只讀方式將位元組讀取到位元組陣列後返回
#!/usr/bin/python3
 
b = bytearray([1,2,3,4,5])
print(b)
print(len(b))

執行結果:

bytearray(b'\x01\x02\x03\x04\x05')
5
  1. 當source引數是一個可迭代物件,那麼這個迭代物件的元素都必須符合0 <= x < 256,以便可以初始化到數組裡
#!/usr/bin/python3
 
b = bytearray([1,2,3,4,5,256])
print(b)
print(len(b))

執行結果:

Traceback (most recent call last):
  File "D:/py/day001/day1/test.py", line 3, in <module>
    b = bytearray([1,2,3,4,5,256])
ValueError: byte must be in range(0, 256)

原文地址

Python內建函式—bytearray
我覺得這篇總結得非常好,為了防止下次要用的時候找不著,因此轉載。