Python bytes() Function
The Python bytes() function returns a bytes object. The function converts objects into bytes objects or create empty bytes object of specified size.
Please note that, the returned bytes object from bytes function can not be modified, whereas the returned bytearray object from bytearray function is modifiable.
Syntax
bytes(source, encoding, errors)
Parameters
source |
Optional. Specify the source to use when creating bytes object. Different source parameter type can be used with this function as described below:
|
encoding |
Optional. Specify encoding of the literal. |
errors |
Optional. Specify response when encoding fails. |
Example:Using bytes() function
In the example below, bytes() function is used to convert a string and integer into a bytes object.
MyStr = "Hello" MyInt = 5 print(bytes(MyStr, 'utf-8')) print(bytes(MyInt))
The output of the above code will be:
b'Hello' b'\x00\x00\x00\x00\x00'
Example:Using bytes() function with iterable
In the example below, bytes() function is used to convert an iterable into a bytes object.
MyList = [10, 20, 30] print(bytes(MyList))
The output of the above code will be:
b'\n\x14\x1e'
❮ Python Built-in Functions