What is the random.randbytes() method in Python?

Overview

The randbytes method of the random module is used to generate bytes of the given size. This method was introduced in Python (version 3.9).

Method signature

randbytes(n)

Parameters

  • n: The size of bytes that we generate.

Return value

The method returns bytes of size n.

Code

import random
no_of_bytes = 5
rand_bytes = random.randbytes(no_of_bytes)
print(rand_bytes)

Code explanation

  • Line 1: We import the random module.
  • Line 3: We define the number of bytes that are generated i.e no_of_bytes.
  • Line 5: We generate random bytes using the method randbytes passing the value for n as no_of_bytes.
  • Line 7: We print the generated random bytes.

Free Resources