Python bytes()

Python bytes() builtin function is used to create an immutable bytes object from given source or of given size.

In this tutorial, we will learn about the syntax of Python bytes() function, and learn how to use this function with the help of examples.

Syntax

The syntax of bytes() function is

bytes(]])

where

ParameterRequired/OptionalDescription
sourceOptionalThe source can be an integer, string, iterable or an object that conforms to the buffer interface.
encodingOptional. Required if source is string,The encoding of the the string (if source is string).
errorsOptionalThe action to take if encoding fails.

Returns

The function returns bytes object.

ADVERTISEMENT

Examples

1. bytes(string, encoding)

In this example, we will give string as argument to the bytes() function. The function returns a bytes object created from the string and encoding data.

Python Program

source = "helloworld"
encoding = 'utf-8'
bytes1 = bytes(source, encoding)
print(f'Return Value: {bytes1}')
Try Online

Output

Return Value: b'helloworld'

In this example, we will give string as argument to the bytes() function, but without encoding.

Python Program

source = "helloworld"
bytes1 = bytes(source)
print(f'Return Value: {bytes1}')
Try Online

Output

Traceback (most recent call last):
  File "d:/workspace/python/example.py", line 2, in <module>
    bytes1 = bytes(source)
TypeError: string argument without an encoding

2. bytes(integer)

In this example, we will give integer for source parameter to the bytes() function. The bytes() function returns a bytes object with size equal to given integer, and each item in the bytes as \x00.

Python Program

source = 8
bytes1 = bytes(source)
print(f'Return Value: {bytes1}')
Try Online

Output

Return Value: b'\x00\x00\x00\x00\x00\x00\x00\x00'

3. bytes(list)

In this example, we will give list of integers as source to the bytes() function. The function returns a bytes object created from this list of integers. The values in the list should be only integers with values ranging from 0 to 255.

Python Program

source = [65, 66, 67, 68]
bytes1 = bytes(source)
print(f'Return Value: {bytes1}')
Try Online

Output

Return Value: b'ABCD'

If any integer value in the list is out of range for a byte, then bytes() throws ValueError, as shown in in the following program.

Python Program

source = [65, 66, 67, 68, 362]
bytes1 = bytes(source)
print(f'Return Value: {bytes1}')
Try Online

Output

Traceback (most recent call last):
  File "d:/workspace/python/example.py", line 2, in <module>
    bytes1 = bytes(source)
ValueError: bytes must be in range(0, 256)

Conclusion

In this Python Tutorial, we have learnt the syntax of Python bytes() builtin function, and also learned how to use this function, with the help of Python example programs.