bytes() Function in Python

Python bytes() Function

The bytes() function in Python is used to create a new immutable bytes object. It can take different types of arguments and convert them into a bytes object.Here is the syntax for the bytes() function:

bytes(source, encoding, errors)
  • The source argument specifies the input that will be converted to bytes. It can be a string, iterable, integer, or a buffer-like object.
  • The optional encoding parameter specifies the character encoding to be used while converting a string to bytes. If not provided, the default encoding is 'utf-8'.
  • The optional errors parameter specifies how encoding and decoding errors should be handled. Possible values are 'strict' (default), 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace', and others.

Here are some examples of using the bytes() function:

Example 1: Converting a string to bytes:

my_string = "Hello, world!"
my_bytes = bytes(my_string, encoding='utf-8')
print(my_bytes)

Example 2: Creating bytes from a list of integers:

my_list = [65, 66, 67]
my_bytes = bytes(my_list)
print(my_bytes)

Example 3: Creating bytes from a buffer-like object:

my_buffer = bytearray([72, 101, 108, 108, 111])
my_bytes = bytes(my_buffer)
print(my_bytes)

The bytes() function returns a new bytes object that represents the input data. The resulting bytes object is immutable, meaning its contents cannot be modified after creation.