
Python Random String: How to make a random string in Python
Following is an example to get a random string in Python.
import random
import string
def random_string(length: int):
s = ''
for i in range(length):
s += random.choice(string.digits + string.ascii_letters)
return s
print(random_string(4)) # 82FE
print(random_string(5)) # DwQWk
The argument is length of string.
string.digits
string
module has a constant string digits
. digits looks like a list from 0 to 9 but is a string by concatenating 10 digits.
a = string.digits
print(a) # 0123456789
print(type(a)) # <class 'str'>
digits
is a string, not list.
string.ascii_letters
ascii_letters is also a constant string.
a = string.ascii_letters
print(a)
# abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
print(type(a))
# <class 'str'>
string.ascii_lowercase
a = string.ascii_lowercase
print(a)
# abcdefghijklmnopqrstuvwxyz
print(type(a))
# <class 'str'>
string.ascii_uppercase
a = string.ascii_uppercase
print(a)
# ABCDEFGHIJKLMNOPQRSTUVWXYZ
print(type(a))
# <class 'str'>
string.punctuation
a = string.punctuation
print(a)
# !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(type(a))
# <class 'str'>
Another example
The function that returns a random string containing digits, alphabets and symbols is like this.
import random
import string
def random_string(length: int):
s = ''
for i in range(length):
s += random.choice(string.digits + string.ascii_letters + string.punctuation)
return s
print(random_string(12)) # -1/3aYKNL?FX
print(random_string(15)) # RG$}`e`Ti6Je%4Y
This can be used to create a token or initial password.
Comments
Powered by Markdown