23
loading...
This website collects cookies to deliver better user experience
bytearray()
function returns a bytearray object that means it converts an object into bytearray objects, which is an array of given bytes.bytearray()
method provides mutable sequence of objects in the range of 0 <= x < 256
bytes()
method.bytearray()
method is:**bytearray([source[, encoding[, errors]]])**
bytearray()
method takes three optional parameters.Type | Description |
---|---|
String | Converts the given string into bytes using str.encode() . In the case of a string, you must also pass encoding as an argument and, optionally errors
|
Integer | Creates an array of provided size and initializes with null bytes |
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. The iterable should be of integers and the range should be in between 0 <= x < 256
|
No source (arguments) | An array of size 0 is created. |
bytearray()
function returns an array of bytes of the given size.# size of array
size = 6
# bytearray() will create an array of given size
# and initialize with null bytes
arr = bytearray(size)
print(arr)
bytearray(b'\x00\x00\x00\x00\x00\x00')
str.encode()
. In the case of a string, you must also pass encoding as an argument and, optionally, errors.# string declaration
string = "Hello World !!!"
# string with encoding 'utf-8'
arr1 = bytearray(string, 'utf-8')
print(arr1)
# string with encoding 'utf-16'
arr2 = bytearray(string, 'utf-16')
print(arr2)
bytearray(b'Hello World !!!')
bytearray(b'\xff\xfeH\x00e\x00l\x00l\x00o\x00 \x00W\x00o\x00r\x00l\x00d\x00 \x00!\x00!\x00!\x00')
0 <= x < 256
# list of integers
lst = [1, 2, 3, 4, 5]
# iterable as source
arr = bytearray(lst)
print(arr)
print("Count of bytes:", len(arr))
bytearray(b'\x01\x02\x03\x04\x05')
Count of bytes: 5
bytearray()
, an array of size 0 is created.# array of size 0 will be created
# iterable as source
arr = bytearray()
print(arr)
bytearray(b'')