In this tutorial, we will understand about the python bytes() method and its uses.

The python bytes() method converts a given object and returns an immutable byte representation of a given object and data.
The syntax of bytes() method is
If you like to use the mutable version you can try the bytearray() method.
Python bytes() Parameters
bytes() takes three optional parameters:
- given_object: The object that has to be converted.
- Encoding: String representation of the encoding method in case the given object is a string.
- error: Method to handle error in case conversion fails.
The given_object parameter can be used to initialize the byte array in the following ways:
- Integer: Returns array of size initialized to null.
- String: Return the bytes of the given string.
- Object: Just the buffer of the given object.
- Iterable: An array of iterable size will return with elements equal to iterable elements.
- No Source: Returns array with size 0.
Now let’s see some examples of the bytes() method.
Example 1: How to convert integer to string using bytes().
The output will be as follow.
Example 2: how to use bytes to convert string to bytes.
The output will be as follow.
Example 3: How to convert iterable to bytes.
Output: