The bytearray() function is a built-in function in Python that returns a mutable sequence of bytes. It can be used to create byte arrays from various sources and to modify existing byte arrays.
Here are some examples of using bytearray():
|
my_string = "Hello, world!"
my_bytes = bytearray(my_string, "utf-8")
print(my_bytes)
|
In this example, we create a string containing the text "Hello, world!", and then use bytearray() to create a byte array from the string, using the "utf-8" encoding. The resulting byte array contains the ASCII codes for each character in the string.
|
my_list = [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]
my_bytes = bytearray(my_list)
print(my_bytes)
|
In this example, we create a list of integers representing the ASCII codes for the characters in the string "Hello, world!", and then use bytearray() to create a byte array from the list. The resulting byte array is equivalent to the one created in the previous example.
|
my_bytes = bytearray(b"abcdef")
my_bytes[1] = 120
print(my_bytes)
|
In this example, we create a byte array containing the bytes "abcdef", and then modify the second byte (index 1) to have the value 120 (which is the ASCII code for the lowercase letter "x"). The resulting byte array contains the bytes "axcdef".
The bytearray() function can be useful in a variety of situations where you need to work with bytes or modify byte arrays. It provides a simple and efficient way to create and manipulate byte arrays in Python.
It's worth noting that the bytearray() function is similar to the bytes() function, which also returns a sequence of bytes. However, bytearray() returns a mutable byte array, while bytes() returns an immutable bytes object. If you need to modify the bytes in your sequence, you should use bytearray(). If you only need to read the bytes, you can use bytes() for improved performance and memory usage.