bytes() Builtin Function

Python – bytes()

Python bytes() builtin function returns an empty bytes object when no arguments passed, bytes object of specific size when size is specified, or a bytes object created from the given string object and encoding.

Syntax

The syntax of bytes() function is

bytes(x, encoding, error)

where

  • x source for bytes object
    • if x is integer, then bytearray() returns a byte array of this size.
    • if x is string, then bytearray() returns byte array created using the characters in the string, and specified encoding.
  • encoding is the encoding to be used, if x is a string.
  • error is the action to be performed if encoding fails.

Note: Individual bytes of the bytes object cannot be modified.

Examples

bytes() with integer as argument

In the following program, we pass a positive integer to bytes() function, to create a bytes object of the specified size. '\x00' is initial value for the bytes in the bytes object.

Python Program

x = 5
output = bytes(x)
print(f'x        : {x}')
print(f'bytes(x) : {output}')
Run

Output

x        : 5
bytes(x) : b'\x00\x00\x00\x00\x00'

bytes() with string as argument

In the following program, we pass a string value to bytes() function, to create bytes object from the input string. We specify the encoding 'utf-8'.

Python Program

x = 'apple'
output = bytes(x, 'utf-8')
print(f'x        : {x}')
print(f'bytes(x) : {output}')
Run

Output

x        : apple
bytes(x) : b'apple'

Summary

In this tutorial of Python Examples, we learned the syntax of bytes() function, and how to create a bytes object of specific size, or a bytes object initialised using string argument, with examples.