Generate a random string using random.choices()

This random.choices() function of a random module can help us achieve this task, and provides a one-liner alternative to a whole loop that might be required for this particular task. Works with Python > v3.6. 

Example 1: Random string generation with upper case letters

Python3




import string
import random
 
# initializing size of string
N = 7
 
# using random.choices()
# generating random strings
res = ''.join(random.choices(string.ascii_uppercase +
                             string.digits, k=N))
 
# print result
print("The generated random string : " + str(res))


Output :

The generated random string : 0D5YE91

Example 2: Generate a random string of a given length in Lowercase

Python3




import string
import random
 
# initializing size of string
N = 7
 
# using random.choices()
# generating random strings
res = ''.join(random.choices(string.ascii_lowercase +
                             string.digits, k=N))
 
# print result
print("The generated random string : " + str(res))


Output:

The generated random string : ipxktny

Example 3: Generate a random string of a given length in Uppercase and Lowercase

Python3




import string
import random
 
# initializing size of string
N = 7
 
# using random.choices()
# generating random strings
res = ''.join(random.choices(string.ascii_letters, k=N))
 
# print result
print("The generated random string : " + str(res))


Output:

The generated random string : ALpxvmI

Python | Generate random string of given length

The issue of generation of random numbers is quite common, but sometimes, we have applications that require us to better that and provide some functionality of generating a random string of digits and alphabets for applications such as passwords. Let’s discuss certain ways in which this can be performed in Python. Here, we will use Random string generation with upper case letters and digits

Similar Reads

Method 1: Generate a random string using random.choices()

This random.choices() function of a random module can help us achieve this task, and provides a one-liner alternative to a whole loop that might be required for this particular task. Works with Python > v3.6....

Method 2: Generate random string using secrets.choice()

...

Contact Us