Python - AI 助手

Python random.randbytes() 函式



Python 的 **random.randbytes()** 函式用於生成 n 個隨機位元組。此函式是 random 模組的一部分,該模組提供各種用於生成隨機數和序列的函式。此函式的主要用途是建立隨機位元組序列,這在測試、模擬或任何需要隨機二進位制資料的場景中都很有用。

但是,需要注意的是,此函式不應用於生成安全令牌或加密金鑰,因為它不能保證加密安全性。為此類目的,可以使用 **secrets.token_bytes()**。

此函式不能直接訪問,因此我們需要匯入 random 模組,然後需要使用 random 靜態物件呼叫此函式。

語法

以下是 Python **random.randbytes()** 函式的語法:

random.randbytes(n)

引數

此函式接受以下引數:

  • **n** - 要生成的位元組大小。

返回值

此函式返回指定大小的隨機生成的位元組序列。

示例 1

讓我們來看一個如何使用 Python 的random.randbytes()函式生成 8 個隨機位元組的示例。

import random

random_bytes = random.randbytes(8)

print(random_bytes)

執行上述程式時,會產生以下結果:

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

示例 2

此示例生成一個隨機十六進位制數,這裡我們使用random.randbytes()函式建立一個隨機位元組序列,然後將其轉換為十六進位制字串。

import random

# Generate 8 random bytes
random_bytes = random.randbytes(8)

# Convert bytes to hexadecimal string
random_hex = random_bytes.hex()

print(random_hex)

上述程式碼的輸出如下:

08f3000d23c7f2be

示例 3

這是另一個示例,它使用random.randbytes()函式生成隨機位元組,然後使用bytes.hex()函式將生成的隨機位元組轉換為十六進位制字串,最後切換十六進位制字串的大小寫。

import random

# Generate 2 random bytes
random_bytes = random.randbytes(2) 
print("2 random Bytes",random_bytes)

# Convert bytes to hexadecimal string
random_hex = random_bytes.hex()
print("Hexadecimal string",random_hex)

# Swap the case of hexadecimal string
result = random_hex.swapcase()
print("Output hexadecimal string", result)

以下是上述程式碼的輸出:

2 random Bytes b'\xa6\xc0'
Hexadecimal string a6c0
Output hexadecimal string A6C0
python_modules.htm
廣告