Python bytes() Method

The bytes() method returns an immutable object of the bytes class initialized with integers' sequence in the range of 0 to 256.

Syntax:

bytes(source, encoding, errors)

Parameters:

  1. source: (Optional) An integer or iterable to convert it to a byte array.
    1. If the source is a string, it must be with the encoding parameter.
    2. If the source is an integer, the array will have that size and will be initialized with null bytes.
    3. If the source is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.
    4. If the source is the iterable object, it must have integer elements in the range 0 to 256.
  2. encoding: (Optional) The encoding of the string if the source is a string.
  3. errors: (Optional) The action to take if the encoding conversion fails.

Return Value:

Returns a byte object.

The following example converts the given integer to byte.

Example: Convert Int to Bytes
print(bytes(1)) 
print(bytes(2)) 
print(bytes(3)) 
Output
b'\x00'
b'\x00\x00'
b'\x00\x00\x00'

If the source arguement is a string, and no encoding method is specified, a TypeError exception is returned.

Example:
print(bytes('Hello'))
Output
TypeError: string argument without an encoding

The encoding method needs to be specified to get a bytes object from the string, as shown below.

Example: Convert String to Bytes
print(bytes('Hello World','utf-8'))
Output
b'Hello World'

An iterable can also be converted to a bytes object as follows.

Example: Convert Iterable to Bytes
nums = [1, 2, 3, 4, 5]
print(bytes(nums))
Output
b'\x01\x02\x03\x04\x05'
Want to check how much you know Python?