Python bytearray Datatype with Example

Python bytearray Datatype with Example

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:

  1. bytearray(string_data, 'utf-8'): This line creates a bytearray from the given string (string_data) using UTF-8 encoding.

  2. byte_array[0] = 72: Modifies the first byte in the bytearray to have the ASCII code for 'H'.

  3. byte_array[7:12] = b'Universe': Replaces a portion of the bytearray with the bytes representing the string 'Universe'. Note the use of the b prefix to create a bytes literal.

  4. byte_array.decode('utf-8'): Converts the bytearray 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.