📜  Python bytearray()(1)

📅  最后修改于: 2023-12-03 14:45:56.426000             🧑  作者: Mango

Python bytearray()

The bytearray() function in Python returns a mutable bytearray object. It allows you to create an array of bytes, which can be modified and updated.

Syntax

The syntax for using the bytearray() function is as follows:

bytearray(size)
bytearray(sequence)
bytearray(string, encoding, errors)
  • The size parameter is an optional integer representing the desired size of the bytearray.
  • The sequence parameter is an optional iterable (such as a list, tuple, or string) that can be used to initialize the bytearray.
  • The string parameter is an optional string that can be encoded into bytes using the specified encoding and errors parameters. The default encoding is 'utf-8'.
Examples

Create an empty bytearray

arr = bytearray()
print(arr)  # Output: bytearray(b'')

Create a bytearray from a sequence

arr = bytearray([65, 66, 67])
print(arr)  # Output: bytearray(b'ABC')

Create a bytearray from a string

arr = bytearray("Hello, World!", 'utf-8')
print(arr)  # Output: bytearray(b'Hello, World!')
Modifying a bytearray

Since bytearray objects are mutable, you can modify individual elements or slices of the array using assignment operations. Here are a few examples:

arr = bytearray([72, 101, 108, 108, 111])

# Modify individual elements
arr[0] = 67
arr[1] = 111

print(arr)  # Output: bytearray(b'Co110')

# Modify a slice
arr[2:4] = bytearray(b'rr')
print(arr)  # Output: bytearray(b'Corr0')

# Append elements
arr.append(49)
print(arr)  # Output: bytearray(b'Corr01')

# Remove elements
del arr[0:4]
print(arr)  # Output: bytearray(b'01')
Useful Methods

The bytearray() object provides several useful methods for working with byte arrays:

  • append(x): Appends the integer x to the end of the array.
  • extend(iterable): Appends all elements from the iterable to the end of the array.
  • insert(i, x): Inserts the integer x at the specified index i.
  • pop([i]): Removes and returns the element at the specified index i. If no index is provided, it removes and returns the last element.
  • remove(x): Removes the first occurrence of the integer x from the array.
  • reverse(): Reverses the order of the elements in the array.
  • decode(encoding, errors): Decodes the array into a string using the specified encoding and errors parameters.

For more information about the bytearray() function and its methods, you can refer to the Python documentation.