Python Random Reference

Generating random numbers, hashes, UUIDs etc


import random

# Create a random integer in the range "from <= r <= to".
r = random.randint(from, to) 

# Create an integer with 32 randomised bits
n = random.getrandbits(32) 
s = hex(n) # Converts the integer to a hex string with a leading 0x

# randomly pick one item from the list
c = random.choice(["door 1", "door 2", "door 3"]) 

# randomly shuffle the list
s = random.shuffle(["Ace Spades","2 Spades", "3 Spades"]) 


The random module (above) is not designed with security applications in mind. If you need a random number for security purposes use the secrets module.

import secrets
secrets.randbits(32)  # Create an integer with 32 randomised bits

Generate a hard-to-guess temporary URL containing a security token suitable for password recovery applications

import secrets
url = '' + secrets.token_urlsafe(16) # 16 bytes of base64 encoded randomness
print(url) # example:


import hashlib

source = "My important data".encode() # must be a bytes object hence the encoding
hash = hashlib.sha256( source ).hexdigest()
print(hash) # output: 4b027ee690d457ebaa1a5f83715b361514bf404a88b6f17770f5db2685e21dd0


import base64
# URL safe encoding
original = "My message"
encoded_message = base64.urlsafe_b64encode(original.encode())
# URL safe decoding
decoded_str = base64.urlsafe_b64decode(encoded_message).decode()

# Encoding a binary file for http transport
import base64
image = open('deer.gif', 'rb')
image_read =
image_64_encode = base64.encodestring(image_read)
# Transport now... then decode on the other end
image_64_decode = base64.decodestring(image_64_encode) 
image_result = open('deer_decode.gif', 'wb') # create a writable image and write the decoding result

Last example from


import uuid

# UUID1 uses a mix of the timestamp and host MAC address
u = uuid.uuid1()

# UUID4 is a purely randomised number
u = uuid.uuid4()

UTF-8 string encoding

All Python strings are UTF-8 unicode by default

Encode UTF-8 unicode string to bytes array object

s = "My string"
b = s.encode()

Decode bytes array object back to UTF-8 unicode string

b = b'My String' # The output from the above
result = b.decode()
print(result)    # My string
  • Note you can use other UTF encoding methods easy enough. eg str.encode("UTF-16") or bytesarray.decode("UTF-16").