In Python, the bytearray
is a changeable group of bytes. It's like the bytes
data type, but you can modify it directly. Here's an example of using bytearray
:
# Creating a bytearray from a string
string_data = "Hello, World!"
byte_array = bytearray(string_data, 'utf-8')
# Displaying the original bytearray
print("Original bytearray:", byte_array)
# Modifying the bytearray
byte_array[0] = 72 # ASCII code for 'H'
byte_array[7:12] = b'Universe' # b'Universe' is a bytes literal
# Displaying the modified bytearray
print("Modified bytearray:", byte_array)
# Converting the bytearray back to a string
modified_string = byte_array.decode('utf-8')
print("Modified string:", modified_string)
Explanation:
bytearray(string_data, 'utf-8')
: This line creates abytearray
from the given string (string_data
) using UTF-8 encoding.byte_array[0] = 72
: Modifies the first byte in thebytearray
to have the ASCII code for 'H'.byte_array[7:12] = b'Universe'
: Replaces a portion of thebytearray
with the bytes representing the string 'Universe'. Note the use of theb
prefix to create a bytes literal.byte_array.decode('utf-8')
: Converts thebytearray
back to a string using UTF-8 decoding.
Remember that bytearray
can be changed, so you can edit its parts directly. This is helpful when you need to work with binary data and change it in-place.