To generate a random string we need to use the following two Python modules.
String module which contains various string constant which contains
the ASCII characters of all cases. String module contains separate
constants for lowercase, uppercase letters, digits, and special
characters.
random module to perform the random generations.
Let see steps to generate a random string of a fixed length of n.
Use the string constant string.ascii_lowercase to get all the
lowercase letter in a single string.
The string.ascii_lowercase constant contains all lowercase letters.
I.e., 'abcdefghijklmnopqrstuvwxyz' Run for loop n number of times to
pick a single character from a string constant using a random.choice
method and add it to the string variable using a join method. The
choice method used to choose the single character from a list
For example, Suppose you want a random string of length 6 then we can
execute a random.choice() method 6 times to pick a single letter from
the string.ascii_lowercase and add it to the string variable.
Let see the code now.
import random
import string
def randomStringwithDigitsAndSymbols(stringLength=10):
"""Generate a random string of letters, digits and special characters """
password_characters = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(password_characters) for i in range(stringLength))
print("Generating Random String password with letters, digits and special characters ")
print ("First Random String ", randomStringwithDigitsAndSymbols() )
print ("Second Random String", randomStringwithDigitsAndSymbols(10) )
print ("Third Random String", randomStringwithDigitsAndSymbols(10) )
Output:
Generating Random String password with letters, digits and special characters
First Random String password qKDhC++T(4
Second Random String password U+(ew5a[#U
Third Random String password uf-g,s6'pX
Use this link for more details Click here
string.ascii_letters + string.digits + '!@#$%^&*()_'
add em to the mix – Sergstring.printable
isn't what you want because it includes newline, tab, etc? – Phanerogam