21. Bytearrays
Syntax:
- bytearray = bytearray(x, encoding, error)
Returns a bytearray object. It can create empty bytearray object of the specified size or convert objects into bytearray objects.
- Parameters:
x – If x is an integer, an empty bytearray object of the specified size will be created.
x – If x is a String, the encoding is required.
x – If x is an iterable, such as a list, it must be of integers from 0 to 255.
encoding – The encoding of the string such as ‘utf-8’
error – Specifies what to do if the encoding fails.
x = bytearray(4)
print(x)
# Output is bytearray(b'\x00\x00\x00\x00')
x = bytearray("abc123", "utf-8")
print(x)
# Output is bytearray(b'abc123')
21.1. bytearray Methods
The bytearray type in Python provides a variety of methods for manipulating and interacting with byte data. Below are some commonly used methods:
21.2. append
- append(x)
Append a single byte to the end of the bytearray.
Example:
my_ba = bytearray([65, 66, 67]) my_ba.append(68) print(my_ba) # Output is bytearray(b'ABCD')
21.3. append
- extend(iterable)
Extend the bytearray by appending elements from the iterable.
Example:
my_ba = bytearray([65, 66, 67]) my_ba.extend([68, 69]) print(my_ba) # Output is bytearray(b'ABCDE')
21.4. append
- insert(i, x)
Insert a single byte at a given position.
Example:
my_ba = bytearray([65, 66, 67]) my_ba.insert(1, 68) print(my_ba) # Output is bytearray(b'ADBC')
21.5. append
- remove(x)
Remove the first occurrence of a byte.
Example:
my_ba = bytearray([65, 66, 67, 66]) my_ba.remove(66) print(my_ba) # Output is bytearray(b'ACB')
21.6. append
- pop([i])
Remove and return a byte at a given position. If no index is specified, removes and returns the last byte.
Example:
my_ba = bytearray([65, 66, 67]) byte = my_ba.pop(1) print(byte) # Output is 66 print(my_ba) # Output is bytearray(b'AC')
21.7. append
- clear()
Remove all bytes from the bytearray.
Example:
my_ba = bytearray([65, 66, 67]) my_ba.clear() print(my_ba) # Output is bytearray(b'')
21.8. append
- count(x)
Return the number of occurrences of a byte.
Example:
my_ba = bytearray([65, 66, 67, 66]) count = my_ba.count(66) print(count) # Output is 2
21.9. append
- find(sub[, start[, end]])
Return the lowest index where the subsequence is found.
Example:
my_ba = bytearray(b'Hello, World!') index = my_ba.find(b'World') print(index) # Output is 7
21.10. append
- reverse()
Reverse the bytes in place.
Example:
my_ba = bytearray([65, 66, 67]) my_ba.reverse() print(my_ba) # Output is bytearray(b'CBA')
21.11. append
- decode(encoding='utf-8', errors='strict')
Decode the bytearray to a string using the specified encoding.
Example:
my_ba = bytearray(b'Hello, World!') string = my_ba.decode('utf-8') print(string) # Output is Hello, World!