Python | bytearray() function
bytearray()
method returns a bytearray object which is an array of given bytes. It gives a mutable sequence of integers in the range 0 <= x < 256.
Syntax:
bytearray(source, encoding, errors)
Parameters:
source[optional]: Initializes the array of bytes encoding[optional]: Encoding of the string errors[optional]: Takes action when encoding fails
Returns: Returns an array of bytes of the given size.
source parameter can be used to initialize the array in few different ways. Let’s discuss each one by one with help of examples.
Code #1: If a string, must provided encoding and errors parameters, bytearray()
converts the string to bytes using str.encode()
str = "Geeksforgeeks" # encoding the string with unicode 8 and 16 array1 = bytearray( str , 'utf-8' ) array2 = bytearray( str , 'utf-16' ) print (array1) print (array2) |
Output:
bytearray(b'Geeksforgeeks') bytearray(b'\xff\xfeG\x00e\x00e\x00k\x00s\x00f\x00o\x00r\x00g\x00e\x00e\x00k\x00s\x00')
Code #2: If an integer, creates an array of that size and initialized with null bytes.
# size of array size = 3 # will create an array of given size # and initialize with null bytes array1 = bytearray(size) print (array1) |
Output:
bytearray(b'\x00\x00\x00')
Code #3: If an Object, read-only buffer will be used to initialize the bytes array.
# Creates bytearray from byte literal arr1 = bytearray(b "abcd" ) # iterating the value for value in arr1: print (value) # Create a bytearray object arr2 = bytearray(b "aaaacccc" ) # count bytes from the buffer print ( "Count of c is:" , arr2.count(b "c" )) |
Output:
97 98 99 100 Count of c is: 4
Code #4: If an Iterable(range 0<= x < 256), used as the initial contents of an array.
# simple list of integers list = [ 1 , 2 , 3 , 4 ] # iterable as source array = bytearray( list ) print (array) print ( "Count of bytes:" , len (array)) |
Output:
bytearray(b'\x01\x02\x03\x04') Count of bytes: 4
Code #5: If No source, an array of size 0 is created.
# array of size o will be created # iterable as source array = bytearray() print (array) |
Output:
bytearray(b'')
Please Login to comment...