The bytearray() Function returns a bytes object, which is an immutable sequence of integers in the range 0 <=x < 256. If you want mutable sequence of integers, use bytearray() function.
Table of contents
Syntax of bytes() Function
bytes(source, encoding, error)
bytes() Parameters
As mentioned in the syntax of bytes() function, this method can take upto three parameters. All these three parameters are optional, when no parameter is passed to bytes(), it returns the array of size 0.
source (Optional) – It initializes the array of bytes. If the source is an integer, an empty bytearray object of the specified size is created and if the source is a String, make sure that you specify the encoding of the source.
encoding (Optional) – You must also provide encoding if the source is a string.
errors (Optional) – Actions that needs to be taken when the encoding of string fails.
Return value from bytes() function
The bytes() method returns an array of bytes of the given size.
Example 1: String to bytes array using bytes() function
When we pass the string to the bytes() method, we must also provide the encoding. In the following example, we are using two different encoding for the same string, as you can see in the output, we are getting different bytes object for each encoding.
str = "beginnersbook" # encoding 'utf-8' arr = bytes(str, 'utf-8') #encdoing 'utf-16' arr2 = bytes(str, 'utf-16') print(arr) print(arr2)
Output:
Example 2: Array of bytes from an integer
When an integer value is passed to the bytes() method, it creates an array of that size (size = integer value) and initializes the elements with null bytes. In the following example, we are passing the value 6 to the bytes() method so the function created an array of size 6 and initialized the elements with null bytes.
number = 6 arr = bytes(number) print(arr)
Output:
b'\x00\x00\x00\x00\x00\x00'
Example 3: bytes object from a list
In the following example we are passing a list to the bytes() method and it returns an immutable sequence of bytes.
lis = [1, 2, 3, 4, 5] arr = bytes(lis) print(arr)
Output:
b'\x01\x02\x03\x04\x05'
Example 4: When no parameter is passed to the bytes() method
If no parameter is passed to the bytes() method, it creates an array of size 0.
arr = bytes() print(arr)
Output:
b''
For further reading:
Leave a Reply