The bytearray() method returns an array of bytes.
Syntax
bytearray(]]) source - source to initialize the array of bytes
- string – Converts the string to bytes using
str.encode()
- integer – Creates an array of provided size, all initialized to null
- iterable – Creates an array of size equal to the iterable count . Iterable integers must be between
0 <= x < 256
- Without an argument an array size will be set to 0
encoding - if the source is a string, the encoding of the string. Ex. utf-8,ascii
errors - action to take when the encoding conversion fails
Examples
byte array from string
s = "String example"
ex = bytearray(s, 'ascii')
print(ex)
Output
bytearray(b'String exapmle')
Creating byte array from integer
#integer creates array of 3
i = 3
ex = bytearray(i)
print(ex)
Output
bytearray(b'\x00\x00\x00')
Creating byte array from iterable list
list = [1,2,3]
ex = bytearray(list)
print(ex)
Output
bytearray(b'\x01\x02\x03')