Python bytearray() Function
Returns either an empty bytearray object of a given size, or a bytearray object from the bytes in the source object
Syntax
Python
Copy Code
bytearray(size) bytearray(source, encoding, error)
Parameters
Parameter | Description |
---|---|
size |
Required. The size of the empty bytearray object to be created. |
source |
Required if more than 1 parameter. The item to be used to populate bytearray
object. If source is String, ensure you specify the encoding of the
source. |
encoding |
Optional. The encoding of the string. Required if source is a string. Typical values are ‘ascii’, ‘utf-8’, or ‘windows-1252’. See the codecs module for more. |
error |
Optional. The manner in which to handle errors. See the
codecs module for more information. All encoders implement, at the least,
|
Example
Python
Copy Code
print(f'Marc as a byte array encoded as utf-8: {bytearray("Marc", "utf-8")}') print(f'Marc as a byte array encoded as utf-16: {bytearray("Marc", "utf-16")}')
Output
Marc as a byte array encoded as utf-8: bytearray(b'Marc') Marc as a byte array encoded as utf-16: bytearray(b'\xff\xfeM\x00a\x00r\x00c\x00')