Python bytearray() Method
The bytearray()
method returns a bytearray object, which is an array of the given bytes. The bytearray class is a mutable sequence of integers in the range of 0 to 256.
Syntax:
bytearray(source, encoding, errors)
Parameters:
- source: (Optional) An integer or iterable to convert it to a byte array.
- If the source is a string, it must be with the encoding parameter.
- If the source is an integer, the array will have that size and will be initialized with null bytes.
- If the source is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.
- If the source is the iterable object, it must have integer elements only in the range 0 to 256.
- encoding: (Optional) The encoding of the string if the source is a string.
- errors: (Optional) The action to take if the encoding conversion fails.
Return Value:
Returns an array of bytes.
The following example converts integer to bytearrays.
print(bytearray(1)) # A byte array of size 1
print(bytearray(2)) # A byte array of size 2
print(bytearray(3)) # A byte array of size 3
bytearray(b'\x00')
bytearray(b'\x00\x00')
bytearray(b'\x00\x00\x00')
If the source
argument is a string and no encoding method is specified, a TypeError
exception is returned.
print(bytearray('Hello World'))
TypeError: string argument without an encoding
The encoding method needs to be specified to return a bytearray object of the string, as shown below.
print(bytearray('Hello World','utf-8'))
bytearray(b'Hello World')
An iterable can also be converted to a bytearray object, as shown below.
nums = [1, 2, 3, 4, 5]
print(bytearray(nums))
bytearray(b'\x01\x02\x03\x04\x05')