python's method of randomly generating passwords of specified length

  • 2020-05-05 11:26:53
  • OfStack

This article illustrates an python method for randomly generating passwords of specified length. Share with you for your reference. The details are as follows:

The python code below generates a random password

of a specified length by randomly combining various characters

The string object in python has several common methods for outputting various characters:


string.ascii_letters

Output all

characters of ascii code

string.digits

Output '0123456789'.  


string.punctuation

The punctuation in ascii is


print string.ascii_letters
print string.digits
print string.punctuation

The output is as follows:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
!"#$% & '()*+,-./:; < = > ?@[\]^_`{|}~

The following code is used to generate the random password


import string
from random import *
characters = string.ascii_letters + string.punctuation + string.digits
password = "".join(choice(characters) for x in range(randint(8, 16)))
print password

I hope this article is helpful for your Python programming.


Related articles: