In this article we will see how how to generate a random string with a given length. This will be useful in creating random passwords or other programs where randomness is required.
With random.choices
The choices function in random module can produce strings which can then be joined to create a string of given length.
Example
import string import random # Length of string needed N = 5 # With random.choices() res = ''.join(random.choices(string.ascii_letters+ string.digits, k=N)) # Result print("Random string : ",res)
Output
Running the above code gives us the following result −
Random string : nw1r8
With secrets
The secrets module also has choice method which can be used to produce random string. But here we can input different conditions from the string module such as lowercase letters only all the digits also.
Example
import string import secrets # Length of string needed N = 5 # With random.choices() res = ''.join(secrets.choice(string.ascii_lowercase + string.digits) for i in range(N)) # Result print("Random string : ",res)
Output
Running the above code gives us the following result −
Random string : p4ylm