當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python bytearray()用法及代碼示例

bytearray()方法返回一個bytearray對象,該對象是給定字節的數組。它給出了一個可變的整數序列,範圍為0 <= x <256。

用法:

bytearray(source, encoding, errors)

參數:


source[optional]:Initializes the array of bytes
encoding[optional]:Encoding of the string
errors[optional]:Takes action when encoding fails

返回值:返回給定大小的字節數組。

source參數可以幾種不同的方式用於初始化數組。讓我們通過示例逐一討論。

代碼1:如果是字符串,必須提供編碼和錯誤參數,bytearray()使用以下命令將字符串轉換為字節str.encode()

str = "Geeksforgeeks"
  
# encoding the string with unicode 8 and 16 
array1 = bytearray(str, 'utf-8') 
array2 = bytearray(str, 'utf-16') 
  
print(array1) 
print(array2)

輸出:

bytearray(b'Geeksforgeeks')
bytearray(b'\xff\xfeG\x00e\x00e\x00k\x00s\x00f\x00o\x00r\x00g\x00e\x00e\x00k\x00s\x00')


代碼2:如果是整數,則創建該大小的數組,並用空字節初始化。

# size of array 
size = 3
  
# will create an array of given size  
# and initialize with null bytes 
array1 = bytearray(size) 
  
print(array1)

輸出:

bytearray(b'\x00\x00\x00')


代碼3:如果是Object,則隻讀緩衝區將用於初始化bytes數組。

# Creates bytearray from byte literal 
arr1 = bytearray(b"abcd") 
  
# iterating the value 
for value in arr1:
    print(value) 
      
# Create a bytearray object 
arr2 = bytearray(b"aaaacccc") 
  
# count bytes from the buffer 
print("Count of c is:", arr2.count(b"c"))

輸出:

97
98
99
100
Count of c is:4


代碼4:如果Iterable(範圍0 <= x <256),則用作數組的初始內容。

# simple list of integers 
list = [1, 2, 3, 4] 
  
# iterable as source 
array = bytearray(list) 
  
print(array) 
print("Count of bytes:", len(array))

輸出:

bytearray(b'\x01\x02\x03\x04')
Count of bytes:4

代碼5:如果沒有源,則創建大小為0的數組。

# array of size o will be created 
  
# iterable as source 
array = bytearray() 
  
print(array)

輸出:

bytearray(b'')


相關用法


注:本文由純淨天空篩選整理自Shivam_k大神的英文原創作品 Python | bytearray() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。