How to generate a secure token, password, or random string in Python (with secrets module)

This code is an example to generate a random string for secure tokens.

import secrets
import string

def gen_rand_str(n: int):
    if n < 1:
        return ''

    a = string.digits + string.ascii_letters + string.punctuation
    s = ''

    for i in range(n):
        s = s + secrets.choice(a)

    return s

r = gen_rand_str(24)
print(r)  # +HqzKJ"a:"Ui}=R2m3%@}W'Q

Since Python 3.6., secrets module has been used to generate random strings. string.punctuation is a set of symbols so if you remove that, a generated string has only alphanumeric letters.

Python String

Python Tutorial