Python bytearray() Function
Description
bytearray()The method returns a new byte array. The elements in this array are mutable, and the value range of each element is: 0 <= x < 256.
Syntax
The syntax of the bytearray() method is:
class bytearray([source[, encoding[, errors]]])
Parameters
- If source is an integer, an initialized array of length source is returned;
- If source is a string, the string is converted into a byte sequence according to the specified encoding;
- If source is an iterable type, the elements must be integers in [0, 255];
- If source is an object compatible with the buffer interface, this object can also be used to initialize bytearray.
- If no parameters are provided, the default is an initialized array with 0 elements.
Return Value
Returns a new byte array.
Examples
The following example demonstrates the usage of bytearray():
>>>bytearray()
bytearray(b'')
>>> bytearray([1,2,3])
bytearray(b'\x01\x02\x03')
>>> bytearray('example', 'utf-8')
bytearray(b'example')
>>>
Python Built-in Functions