当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。