How to Generate a Random String in Python


Python gives the ability to generate random strings out of the box, by using a combination of the string and random modules.

import string
import random

# How many characters do you want
S = 10

# Call random.choices() string module to find the string in Uppercase + numeric data.  
ran = ''.join(random.choices(string.ascii_uppercase + string.digits, k = S))    

# Print the result
print("The randomly generated string is : " + str(ran))