Python bytearray()

Python bytearray() function returns a bytearray object that contains the array of bytes from the input source. The bytearray class is mutable, so we can change its element values.

Python bytearray()函数返回一个bytearray对象,其中包含来自输​​入源的字节数组。 bytearray类是可变的,因此我们可以更改其元素值。

Python bytearray() (Python bytearray())

Python bytearray() function syntax is:

Python bytearray()函数语法为:

class bytearray(]])

source is used to initialize the bytearray object array elements. This is an optional argument.

source用于初始化bytearray对象数组元素。 这是一个可选参数。

encoding is optional unless source is string. It’s used for converting the string to bytes using str.encode() function.

除非source是string,否则encoding是可选的。 它用于使用str.encode()函数将字符串转换为字节。

errors is optional parameter. It’s used if the source is string and encoding fails due to some error.

errors是可选参数。 如果源是字符串并且由于某些错误而编码失败,则使用它。

There are some specific rules followed by bytearray() function depending on the type of source.

根据源类型,有一些特定的规则,后跟bytearray()函数。

  • If no argument is passed, empty byte array is returned.

    如果未传递任何参数,则返回空字节数组。
  • If source is integer, it initializes the byte array of given length with null values.

    如果source是整数,则使用空值初始化给定长度的字节数组。
  • If source is string, encoding is mandatory and used to convert string to byte array.

    如果source是字符串,则编码是强制性的,用于将字符串转换为字节数组。
  • If source is iterable, such as list, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.

    如果source是可迭代的,例如list ,则它必须是0 <= x <256范围内的整数的可迭代对象,这些整数用作数组的初始内容。

Let’s look at some of the examples of bytearray() function.

让我们看一下bytearray()函数的一些示例。

不带参数的bytearray() (bytearray() with no arguments)

b = bytearray()
print(b)

Output:

输出:

bytearray(b'')

具有字符串和可变性的bytearray() (bytearray() with string and mutability)

# string to bytearray
# encoding is mandatory, otherwise "TypeError: string argument without an encoding"
b = bytearray('abc', 'UTF-8')
print(b)
b[1] = 65  # mutable
print(b)

Output:

输出:

bytearray(b'abc')
bytearray(b'aAc')

具有int参数的bytearray() (bytearray() with int argument)

b = bytearray(5)
print(b)

Output:

输出:

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

具有可迭代的bytearray() (bytearray() with iterable)

b = bytearray([1, 2, 3])
print(b)

Output:

输出:

bytearray(b'\x01\x02\x03')

That’s all for a quick guide of python bytearray() function.

这就是python bytearray()函数的快速指南。

GitHub Repository. GitHub存储库中检出完整的python脚本和更多Python示例。

Reference: Official Documentation

参考: 官方文档

翻译自: https://www.journaldev.com/22703/python-bytearray