Bytearray in python
- Get link
- X
- Other Apps
Bytearray in python
In Python, a bytearray
is a mutable sequence of bytes. It is similar to a bytes
object, but unlike bytes
, a bytearray
can be modified in-place. In this blog, we will explore what a bytearray
is, how to create and modify it, and how it differs from other similar data types.
Creating a Bytearray
A bytearray
can be created using the bytearray()
constructor. The constructor takes an optional argument source
, which can be used to initialize the bytearray
with an iterable of integers, a string, or another bytearray
.
Here's an example of creating a bytearray
from a string:
>>> my_str = "hello world" >>> my_bytearray = bytearray(my_str, "utf-8") >>> print(my_bytearray) bytearray(b'hello world')
In the example above, we created a bytearray
from the string "hello world"
and specified the encoding as "utf-8"
. The resulting bytearray
contains the UTF-8 encoded bytes of the string.
Modifying a Bytearray
One of the main advantages of using a bytearray
over a bytes
object is that it can be modified in-place. This means that individual bytes in the bytearray
can be changed without creating a new object.
To modify a bytearray
, you can simply access its elements using square brackets and assign a new value to them. Here's an example:
>>> my_bytearray = bytearray(b'hello world') >>> my_bytearray[0] = 72 >>> my_bytearray[6:11] = b'WORLD' >>> print(my_bytearray) bytearray(b'HELLO WORLD')
In the example above, we modified the first byte of the bytearray
to be the ASCII value for the letter 'H'
(which is 72), and we replaced the substring "world"
with "WORLD"
.
Converting a Bytearray to Other Data Types
Sometimes you may need to convert a bytearray
to another data type, such as a string or a list of integers. Here are some examples of how to do this:
>>> my_bytearray = bytearray(b'hello world') # Convert to a string >>> my_str = str(my_bytearray, "utf-8") >>> print(my_str) hello world # Convert to a list of integers >>> my_list = list(my_bytearray) >>> print(my_list) [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
In the example above, we converted the bytearray
to a string using the str()
function and the "utf-8"
encoding. We also converted the bytearray
to a list of integers using the list()
constructor.
Conclusion
In this blog, we've explored what a bytearray
is and how to create and modify it. We've also seen how to convert a bytearray
to other data types. bytearray
is a useful data type when you need to work with mutable sequences of bytes, such as when working with binary data or communicating over a network.
Happy Learning!! Happy Coding!!
- Get link
- X
- Other Apps
Comments