Python bytearray() 函数返回一个新的字节数组。它是一个可变的整数序列,范围在 0 <= x < 256 之间。此函数可以将指定的对象转换为 bytearray 对象,也可以创建所需大小的空 bytearray 对象。它是 Python 中的内置函数之一。
字节数组可以从以下来源创建 -
- String − 我们可以通过使用 str.encode() 将字符串编码为字节来从字符串创建 bytearray。
- Integer - 如果源是整数,则将创建一个具有指定大小的 null 值的数组。
- Object − 在这种情况下,使用只读缓冲区来初始化字节数组。
- Iterable − 创建一个大小等于 iterable 长度的数组。
- No source − 如果未指定源,则创建大小为 0 的字节数组。
语法
以下是 Python bytearray() 函数的语法 -
bytearray(source)
or,
bytearray(source, encoding)
or,
bytearray(source, encoding, errors)
参数
Python bytearray() 函数接受三个参数,所有这些参数都是可选的 -
- source − 它表示一个对象,例如列表、字符串或元组。
- encoding − 它表示传递的字符串的编码。
- errors - 它指定编码失败时所需的操作。
返回值
Python bytearray() 函数返回一个新的字节数组。
bytearray() 函数示例
练习以下示例来理解 Python 中 bytearray() 函数的使用:
示例:使用 bytearray() 函数
以下示例显示了 Python bytearray() 函数的用法。这里我们创建了一个空的 bytearray。
empByte_array = bytearray()
print("It is an example of empty bytearray:", empByte_array)
当我们运行上述程序时,它会产生以下结果——
It is an example of empty bytearray: bytearray(b'')
示例:使用 bytearray() 将字符串转换为 bytearray 对象
在下面的代码中,我们将给定的字符串转换为字节数组。为此,我们使用 bytearray() 函数,将 string 和 encoding 作为参数值传递。
byte_arrayStr = "Tutorials Point bytearray"
str_byte_array = bytearray(byte_arrayStr, 'utf-8')
print("Creating bytearray from string:")
print(str_byte_array)
以下是上述代码的输出 -
Creating bytearray from string:
bytearray(b'Tutorials Point bytearray')
bytearray(b'Tutorials Point bytearray')
示例:使用 bytearray() 创建指定大小的 bytearray
下面的代码演示了如何创建指定大小的字节数组。我们将 size 和 value 作为参数传递给 bytearray() 函数。
size = 5
value = 1
new_byte_array = bytearray([value]*size)
print("Bytearray of the given size:")
print(new_byte_array)
上述代码的输出如下 -
Bytearray of the given size:
bytearray(b'\x01\x01\x01\x01\x01')
bytearray(b'\x01\x01\x01\x01\x01')
示例:修改 bytearray
在下面的代码中,使用 bytearray() 函数创建一个 bytearray。然后我们使用 ord() 函数修改它的第 8 个字符。由于 bytearray 对象是可变的,因此可以很容易地对其进行修改。
byte_arr = bytearray('Tuorialspoint', 'utf-8')
print("Original bytearray:", byte_arr)
byte_arr[8] = ord('P')
print("Modified bytearray:", byte_arr)
以下是上述代码的输出 -
Original bytearray: bytearray(b'Tuorialspoint')
Modified bytearray: bytearray(b'TuorialsPoint')
Modified bytearray: bytearray(b'TuorialsPoint')