Contents
How to generate random password string in Python
How to generate random password with Python programming language – Cuongquach.com | Ok, i will introduce you a good way with some neccessary modules to make a strong password (digits + upper character + lower character), the min length of password string will be 8. In this post, i will use Python 2.7 syntax for example, if you choose Python 3.x you need to search document of module.
1. Using module string python
Let’s import module string.
>>> import string
Print a string contains all alphabet characters.
>>> string.letters 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
Print all special characters.
>>> string.punctuation '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
Print a string contains numbers.
>>> string.digits '0123456789'
In this post, i will exclude all special characters in operation of generating random password ? Why ? Because in some OS or applications, they dont accept almost of special characters so we dont need them so much for inconvenience.
Howerver, what we will do next ? We just have few list of needed character for combining operation to make a strong password. Ok, next step we will use module ‘random‘ in Python to make a bit interesting action.
2. Using module random python
Module random in python supports you a lot of useful method for any case like generate random digit, choice an object in list,… in this post we will only need to use method pick a random character once time.
>>> import string, random >>> chars = string.letters >>> print chars 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> random.choice(chars) 't' >>> random.choice(chars) 'V' >>> random.choice(chars) 'J' >>> random.choice(chars) 'a'
– Go to this time, i think we can imagine how sample code will work to create a random password.
3. Sample code to generate random password
In this case, i will fix the min size and max size for length of password (from 8 -> 15).
Run loop ‘for‘ and extract random character in database pre-defined characters. After that, concentrate all of extracted character together without any delimiter.
import string import random chars_fixed = string.letters + string.digits min_size_pass = 8 max_size_pass = 15 password = "".join(random.choice(chars_fixed) for x in range(random.randint(min_size_pass, max_size_pass))) print "This is your password : %s" % password
Output:
This is your password : DZ2b6wjXj8mD This is your password : 6wiu7pcgb
Very easy right, now you can use above code to deploy a function for generate random password. Just do it by yourself.