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
- Check if a string contains the other string
- Check if a string starts with another string
- Split a string
- Concatenate strings
- Get the index of substring
- Get the index of the last occurrence of a substring
- Trim a string
- Replace a substring
- Replace multiple spaces with one space
- Fill 0 letters to a string
- Capitalize a string
- Convert a string lowercase
- Check if a string is numeric
- Check if a string is uppercase
- Parse a string to a float
- Format a string
- f-string
- Reverse a string
- Slice a string
- Subtract a string from another string
- Make a random string
- Generate a secure token
- Encode a string
- Get the sha256 value
- Convert an integer to a hexadecimal string
- Get a character or integer value
- Get digits or ASCII letters
- Center a string
- Convert string to tuple