Python Tutorial Python Advanced Python References Python Libraries

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:
  • String : Converts the string into bytes object. encoding parameter must be provided.
  • Integer : Creates a bytes object of specified size.
  • Object : Creates a bytes object using read-only buffer of the object.
  • Iterable : Creates a bytes object of size equal to the iterable count and initialized to the iterable elements. Iterable must contain elements between 0 <= i < 256.
  • No source : Creates a bytes object of size 0.
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