In many case we face a problem where we have to create a random string or password, Here is something what may help us. Using python i have tryed to do this. Let me know if there is any easy or better way to do this.

I have imported two Python modules

  • string
  • random

The string module

This contains various string constant which contains the ASCII characters of all cases. The string module contains separate constants for lowercase, uppercase letters, digits, and special characters.

Random

This going to perform the random generations for us.

Function Description

def createRandomString(length):
    letters = string.ascii_lowercase
    randomString = ''.join(random.choice(letters) for i in range(length))
    return randomString
  • string.ascii_lowercase this provides us all the lowercase letters. like 'abcdefghijklmnopqrstuvwxyz'
  • Execute for loop length times and use random.choice() to pick a single character from the string constant. At the end of each iteration, add it to the string variable using a join function.The random.choice() function is used to choose a single item from any sequence.

Let's see the outputs for length 8

Sample Outputs

fxhqybvz
ttibggzg
jndjnfjf
idjerefj

Every time you will get a new string.