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.

Method #1 : Using random.choices()

This function of 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 .



filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# generating random strings 
# using random.choices()
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))

chevron_right


Output :

The generated random string : 0D5YE91

 

Method #2 : Using secrets.choice()

For Cryptographically more secure random numbers, this function of secret module can be used as it’s internal algorithm is framed in a way to generate less predictable random numbers. Works with Python > v3.6 .

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# generating random strings 
# using secrets.choice()
import secrets
import string
  
# initializing size of string 
N = 7
  
# using random.choices()
# generating random strings 
res = ''.join(secrets.choice(string.ascii_uppercase + string.digits)
                                                  for i in range(N))
  
# print result
print("The generated random string : " + str(res))

chevron_right


Output :

The generated random string : T7HPKVR


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.