📅  最后修改于: 2023-12-03 14:45:56.426000             🧑  作者: Mango
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.
The syntax for using the bytearray()
function is as follows:
bytearray(size)
bytearray(sequence)
bytearray(string, encoding, errors)
size
parameter is an optional integer representing the desired size of the bytearray.sequence
parameter is an optional iterable (such as a list, tuple, or string) that can be used to initialize the bytearray.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'
.arr = bytearray()
print(arr) # Output: bytearray(b'')
arr = bytearray([65, 66, 67])
print(arr) # Output: bytearray(b'ABC')
arr = bytearray("Hello, World!", 'utf-8')
print(arr) # Output: bytearray(b'Hello, World!')
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')
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.