In this article we will discuss about the bytearray() function in python programming language with the help of examples.
Python bytearray() function
By using the built-in python function, we can convert the collection of integers or strings into mutable byte sequence. In simple terms, the python bytearray() method is used to return an array of specified byte i.e., bytearray which is mutable in the range [0 <= x < 256]
Syntax
bytearray(source, encoding, errors)
Parameter of Python bytearray() function
Python function takes three types of optional parameter which are as follows;
• source- A source in order to initialize the array of bytes.
• encoding- If the source is string, then for the encoding of the string.
• error- If the encoding fails it takes action.
Return value of Python bytearray() function
The python method is used to return an array of specified byte i.e., bytearray which is mutable.
Example 1: Array of bytes from a string
str1 = "Python is Programming Languages."# string with encoding 'utf-8'
array = bytearray(str1, 'utf-8')
print(array)
Output
bytearray(b'Python is Programming Languages.')
Example 2: Array of bytes of given integer size
num = 7array = bytearray(num)
print(array)
Output
bytearray(b'\x00\x00\x00\x00\x00\x00\x00')
Example 3: Array of bytes from an iterable list
li = [11, 12, 13, 14, 15]array = bytearray(li)
print(array)
Output
bytearray(b'\x0b\x0c\r\x0e\x0f')