The bytes and bytearray are the core built-in types in Python to manipulate binary data.
How to use bytes function
The general syntax for using the bytes function is:
Where the source can be an integer, string, Object, or iterable.
All the parameters in the bytes function are optional. So, if the source is not provided, the bytes function creates an array of zero size.
The third parameter error is used when the source is provided as a string and it fails.
An example of using an integer in byte function
The example below uses just the first argument in the bytes function i.e. integer as the source. I provided value 9 and see the output:
#Bytes Demo obj_byte = bytes(2) print (obj_byte)
The result:
The example of using a string in bytes function
In this examples, I used a string and also given the encoding parameter value i.e. “utf-8”. See the code and output:
#Bytes Demo with string obj_byte = bytes("Hello Python", "utf-8") print (obj_byte)
The output:
Note: The TypeError occurs if you do not provide the encoding type there. That is:
The example of bytes with a list
In the example below, we have a list of numeric elements. Remember, the definition of bytes function states that you may use an iterator as the source?
The code below uses a list and displays the returned bytes object:
#Bytes Demo with list lst_num = [1, 15, 25] obj_byte_lst = bytes(lst_num) print (obj_byte_lst)
The result:
What if the list contained a string item?
I just added a string item in the above list and see the output:
#Bytes Demo with list (a string item) lst_mix = [1, 15, 25, "A string"] obj_byte_lst = bytes(lst_mix) print (obj_byte_lst)
The result:
An example of Python bytearray example
As mentioned earlier, the bytes function returns a byte object which is immutable. If you want a mutable object then use the bytearray() function.
The bytearray() function returns a bytearray object that is mutable. The bytearray object is an array of the given bytes.
The syntax for using this function is:
The example below shows using an integer as the source in the bytearray function:
#Bytearray Demo int_x = bytearray(5) print (int_x)
The result:
Using a string in bytearray example
The example below shows using a string in bytearray function.
#Bytearray Demowith string obj_bytearray = bytearray("Python is cool", "utf-8") print (obj_bytearray)
The result: