1. About Python, bytearray() function

In Python, bytearray() is a built-in function that creates a new array of bytes. The bytearray() function is used to create a mutable sequence of bytes from a specified source, such as a string or another sequence of integers.

Syntax

The syntax for bytearray() is as follows:

bytearray(]])

Here:

  1. source: can be an iterable object like a list, tuple or a string.
  2. encoding and errors: are optional parameters and they can be used to specify the encoding of the input source and how to handle encoding errors, respectively.

2. Examples of use of bytearray() function

Here's an example of using bytearray() to create a byte array from a string:

my_string = "Hello, world!"
my_bytearray = bytearray(my_string, 'utf-8')
print(my_bytearray)

The output of the above code will be:

bytearray(b'Hello, world!')

In this example:

  1. we create a string variable my_string: with the value "Hello, world!".
  2. We then create a byte array my_bytearray from my_string using the bytearray(): function and passing in the my_string as the source parameter and 'utf-8' as the encoding parameter.
  3. The resulting byte array: is then printed to the console.





We can modify the contents of a byte array created using bytearray() because it is mutable. For example, we can change the first element of the my_bytearray to the integer value of 72 to represent the ASCII code for the character 'H':

my_bytearray[0] = 72
print(my_bytearray)

The output of the above code will be:

bytearray(b'Hello, world!')

In this example, we modify the first element of the my_bytearray using its index and then print the modified byte array to the console.
Overall, bytearray() is a useful function in Python for creating mutable arrays of bytes that can be modified as needed.

One thought on “Python, bytearray() function”

Leave a Reply