Python | bytearray()函数

bytearray() 方法返回bytearray对象,该对象是给定字节的数组。它给出了0<=x<256范围内的可变整数序列。

null

语法:

bytearray(source, encoding, errors)

参数:

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

返回: 返回给定大小的字节数组。

来源 参数可以用几种不同的方式初始化数组。让我们通过例子逐一讨论。

代码#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'xffxfeGx00ex00ex00kx00sx00fx00ox00rx00gx00ex00ex00kx00sx00')

代码#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'x00x00x00')

代码#3: 如果是对象,只读缓冲区将用于初始化字节数组。

# 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'x01x02x03x04')
Count of bytes: 4

代码#5: 如果没有源,则创建大小为0的数组。

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


输出:

bytearray(b'')
© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享