How I Generated a random string of given length using python
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
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.
This going to perform the random generations for us.
def createRandomString(length): letters = string.ascii_lowercase randomString = ''.join(random.choice(letters) for i in range(length)) return randomString
string.ascii_lowercasethis provides us all the lowercase letters. like
- 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
joinfunction.The random.choice() function is used to choose a single item from any sequence.
Let's see the outputs for length 8
fxhqybvz ttibggzg jndjnfjf idjerefj
Every time you will get a new string.