Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python random.randbytes() Function



The Pythonrandom.randbytes() function in Python is used to generate n random bytes. This function is part of the random module, which provides various functions to generate random numbers and sequences. The primary use of this function is to create random byte sequences, which can be useful in various applications such as testing, simulations, or any scenario where random binary data is required.

However, it is important to note that this fuction should not be used for generating security tokens or cryptographic keys, as it does not guarantee cryptographic security. For such purposes, you can use thesecrets.token_bytes().

This function is not accessible directly, so we need to import the random module and then we need to call this function using random static object.

Syntax

Following is the syntax of the Pythonrandom.randbytes() function −

random.randbytes(n)

Parameters

This function accepts the following parameter −

  • n − Size of the bytes to be generated.

Return Value

This function returns a randomly generated sequence of bytes of the specified size.

Example 1

Let's look at an example of how to use the Pythonrandom.randbytes() function to generate 8 random bytes.

import randomrandom_bytes = random.randbytes(8)print(random_bytes)

When we run the above program, it produces the following result −

b'\xc7\xf8E\x8a\xa4\xb7\xa4\x90'

Example 2

This example generate a random hexadecimal number, here we are using therandom.randbytes() function to create a sequence of random bytes and then convert them to a hexadecimal string.

import random# Generate 8 random bytesrandom_bytes = random.randbytes(8)# Convert bytes to hexadecimal stringrandom_hex = random_bytes.hex()print(random_hex)

The output of the above code is as follows −

08f3000d23c7f2be

Example 3

Here is another example uses therandom.randbytes() function to generate the random bytes, then convert the generated random bytes into hexadecimal string using thebytes.hex() function and finally, swaps the case of the hexadecimal string.

import random# Generate 2 random bytesrandom_bytes = random.randbytes(2) print("2 random Bytes",random_bytes)# Convert bytes to hexadecimal stringrandom_hex = random_bytes.hex()print("Hexadecimal string",random_hex)# Swap the case of hexadecimal stringresult = random_hex.swapcase()print("Output hexadecimal string", result)

Following is an output of the above code −

2 random Bytes b'\xa6\xc0'Hexadecimal string a6c0Output hexadecimal string A6C0
python_modules.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp