Python bytearray() built-in function
From the Python 3 documentation
Return a new array of bytes. The bytearray class is a mutable sequence of integers in the range [...]. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has [...].
Introduction
The bytearray()
function returns a new array of bytes. This object is a mutable sequence of integers in the range 0 <= x < 256. It’s essentially a mutable version of the bytes
object, which means you can change its contents after it’s created. This is useful for handling binary data that needs to be modified in place.
Examples
# Create a bytearray from a string with a specific encoding
ba1 = bytearray("hello", "utf-8")
print(ba1)
# bytearray(b'hello')
# Create a bytearray from a list of integers
ba2 = bytearray([72, 101, 108, 108, 111])
print(ba2)
# bytearray(b'Hello')
# Modify a bytearray (it's mutable)
ba2[0] = 104 # ASCII for 'h'
ba2.append(33) # ASCII for '!'
print(ba2)
# bytearray(b'hello!')