In the browsing of other people's blog when learning the random module, preface self-practice, write a random generation of the specified length of the password string function, come out for your reference:
Nonsense not much to say, on the code:
#Coding:utf-8ImportRandomImportStringspecial_chars='~%#%^&*'Password_chars= string.ascii_letters + string.digits +Special_charsdefGenerate_random_password (password_length=10): """generates a password string of the specified length, and when the password is longer than 3 o'clock, the password contains at least: 1 uppercase letters, +1 lowercase letters, +1 special characters:p Aram Password_length: Length of the password string: return: Password string """char_list=[Random.choice (String.ascii_lowercase), Random.choice (String.ascii_uppercase), Random.choice (SP Ecial_chars),]ifPassword_length > 3: #The Random.choice method returns a list, a tuple, or a string of random items #(x for X in range (N)) returns a generator object #[x for x in range (N)] Returns a list objectChar_list.extend ([Random.choice (Password_chars) for_inchRange (password_length-3)]) #use Random.shuffle to disrupt elements in a listrandom.shuffle (char_list)return "'. Join (Char_list[0:password_length])deftest_password_generate (): Random_password= Generate_random_password (password_length=6) Print(Random_password) test_password_generate ()
Finish the hand, the sister:
python--randomly generates a password of the specified length