Python Glossary Русский

Python 3.6+secretsfunction

secrets.token_hex()

tokens

Returns a random token as hexadecimal text: nbytes random bytes give a string of 2*nbytes characters.

Syntax

secrets.token_hex(nbytes=None) -> str

The argument is a number of bytes, not the string length: token_hex(16) yields 32 characters. A common mistake is passing the desired length and getting a token twice as long. The token contains only 0-9 and a-f, so it is safe in URLs, file names and SQL without escaping.

Examples

import secrets
t = secrets.token_hex(16)
print(len(t))  # → 32 — вдвое больше nbytes
print(all(c in '0123456789abcdef' for c in t))  # → True
print(t)  # → ? случайная строка

See also

Open in the full glossarydocs.python.orgReport an inaccuracy