Python bytearray - bytearray in Python
Last updated on
bytearray in Python
Python bytearray
Python bytearray() method returns an array of bytes of the given size and initialization values. In other words the Python bytearray() function returns a bytearray object. It can convert Python objects into Python bytearray objects, or create empty bytearray object of the specified size.
Syntax of bytearray Method
bytearray([source[, encoding[, errors]]])
All the parameters in bytearray method are optional.
Parameters of bytearray Method
- source : Source to initialize the array of bytes. This is optional parameter.
- encoding : If the source is a string, the encoding of the string. The encoding parameter also optional parameter.
- errors : If the source is a string, the action to take when the encoding conversion fails. This is also optional parameter.
What is a bytearray in Python ?
bytearray() method returns a bytearray object which is mutable can be modified sequence of integers in the range 0 <= x < 256.
How to Use source Parameter of bytearray in Python ?
The source parameter can be used to initialize the byte array.
How to Use source Parameter of bytearray in Python
Data Type | Description |
---|---|
String | Converts the string to bytes using str.encode() Must also provide encoding and optionally errors |
Integer | Creates an array of provided size, all initialized to null |
Object | A read-only buffer of the object will be used to initialize the byte array |
Iterable | Creates an array of size equal to the iterable count and initialized to the iterable elements Must be iterable of integers between 0 <= x < 256 |
No source (arguments) | If no arguments given in bytearray() method it creates an array of size 0. |
How to Create bytearray From String in Python ?
Create Python bytearray From String Example
string_to_bytearray = "Welcome to Python bytearray Tutorial" bytearray_from_string = bytearray(string_to_bytearray, 'utf-8') print(bytearray_from_string)
How to Create Array of bytes from a given size using bytearray in Python ?
Create Array of bytes from a given size using bytearray Example
byte_array_size = 7 empty_byte_array = bytearray(byte_array_size) print(empty_byte_array)
How to Create Array of bytes from iterable List in Python ?
Create Array of bytes from iterable List Example
iterable_list = [1, 2, 3, 4, 5, 6, 7] byte_array_from_list = bytearray(iterable_list) print(byte_array_from_list)