What is bytes() in Python?
The bytes() function converts an object (such as a list, string, integers, etc.) into an immutable bytes object within the range of 0 to 256. If no object is provided to the bytes() method, it can generate an empty bytes object of a specified size.
Syntax
This method can be declared in two ways, depending on the requirement:
Parameters and return value
The return value of the bytes() function varies in two ways depending upon the parameters:
-
If an integer indicating the size of the
bytesis passed into the function, it returns an emptybytesobject of the specified size. -
Instead of a size, a string, tuple, or a list is passed into the
bytes()method, it is converted into a correspondingbytesobject. In this case, the encoding for the string, tuple, or list can be specified, and hence encoding is an optional parameter. -
A third optional argument is passed in the function that tells what to do if the method fails to cater to the errors.
Code
An empty bytes object of a specific size is created in the example below, i.e., 6.
# specify sizesize = 6#generate empty bytes object of size 6:byteArray = bytes(size)# output: b'\x00\x00\x00\x00\x00\x00'print(byteArray)
Here, no specific size of the required bytes is given because an object, i.e., string, is passed into the function. Also, the encoding method “utf-8” is provided in the given instance:
givenString = ["Welcome", "to", "educative"]# given_string is encoded into bytes object according to utf-8byteArray = bytes(givenString,'útf-8')# output: b'Welcome to educatve'print(byteArray)
Similarly, an object, in this case, a tuple is passed into the bytes() function to generate bytes object corresponding to it without mentioning any encoding type.
tup = (1, 2, 3, 4, 5)# tuple is converted into bytes object without specifying any encoding typebyteArray = byte(tup)# outputs: b'\x01\x02\x03\x04\x05'print(byteArray)