Python Practice › OS Module Programs › Program 27
Random bytes with os.urandom()
Write a Python program to get random bytes with os.urandom() and turn them into a string.
Output
bytes 8 16
Approach
os.urandom(n)returns n cryptographically strong random bytes.
Solution
import os data = os.urandom(8)print(type(data).__name__, len(data))print(len(data.hex()))Output
bytes 8 16
Line by line
Line 3
The bytes differ on every run; hex() turns 8 bytes into 16 hexadecimal characters.
Learn the concept
New to this topic? Read the lesson, then come back.