bytearray(source=b'')
class bytearray(source, encoding)
class bytearray(source, encoding, errors)
The bytearray() function returns a bytearray object, which is an array of specified bytes.
Parameters
The bytearray() function accepts three optional parameters:
- source (Optional) — source to initialize the byte array.
- encoding (Optional) — if the source is a string, the encoding of the string.
- errors (Optional) — if the source is a string, action to take when encoding conversion fails.
Return Value
Returns a byte array. The bytearray type is a mutable sequence of integers in the range 0 ≤ X < 256. The source parameter can be used for initial array initialization:
- If
sourceis a string, you must also provideencodingand optionallyerrors. - If
sourceis an integer, the array will have the sizesourceand be initialized with bytes of value0. - If
sourceis an object, it must support the buffer interface. A buffer intended for reading will be used to initialize the byte array. - If
sourceis an iterable, its elements must be integers in the range 0 ≤ X < 256. The array will be initialized with these numbers. - If
sourceis not provided, it returns an emptybytearray.
Examples
bytearray('Hello, Python!', 'utf-8')
# bytearray(b'Hello, Python!')
bytearray(5)
# bytearray(b'\x00\x00\x00\x00\x00')
bytearray([1, 2, 3])
# bytearray(b'\x01\x02\x03')