Python編程生成隨機(jī)用戶名及密碼的方法示例
本文實(shí)例講述了Python編程生成隨機(jī)用戶名及密碼的方法。分享給大家供大家參考,具體如下:
方案一:
import random global userName,userPassword #為了便于使用,定義為全局變量 userName = '' userPassword = '' def get_userNameAndPassword(): global userName, userPassword usableName_char = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+=-><:}{?/" #可作為用戶名的字符 usablePassword_char ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_.1234567890" #可作為密碼的字符,根據(jù)所需可適當(dāng)增減 e_userName = [] #定義一個(gè)臨時(shí)List變量,使用list.append添加字符 e_userPassword = [] for i in range(8): e_userName.append(random.choice(usableName_char)) for j in range(6): e_userPassword.append(random.choice(usablePassword_char)) print"e_userName = ", e_userName #輸出用戶名字符list print"e_userPassword = ", e_userPassword #輸出密碼字符list userName = ''.join(e_userName) userPassword = ''.join(e_userPassword) try: get_userNameAndPassword() print "用戶名:", userName print "密碼:", userPassword except Exception, e: print e.reason
程序輸出:
e_userName = ['q', 'M', '2', 'R', 'B', '}', '6', '='] e_userPassword = ['T', 'O', '4', 'C', 'H', '.'] 用戶名: qM2RB}6= 密碼: TO4CH.
方案二(省去中間變量):
#coding=utf-8 import random global userName,userPassword #為了便于后面使用,定義為全局變量 userName = '' userPassword = '' def get_userNameAndPassword(): global userName, userPassword #8位用戶名及6位密碼 userName = ''.join(random.sample("1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+=-><:}{?/",8)) userPassword = ''.join(random.sample("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_.1234567890",6)) try: get_userNameAndPassword() print "用戶名:", userName print "密碼:", userPassword except Exception, e: print e.reason
程序輸出:
用戶名: GweV?2um 密碼: fwiOZL
常用第二種方法,直觀簡(jiǎn)便。
注:(本例在python2.7下測(cè)試正常運(yùn)行。)
PS:這里再為大家提供兩款相關(guān)在線工具供大家參考使用:
在線隨機(jī)數(shù)字/字符串生成工具:
http://tools.jb51.net/aideddesign/suijishu
高強(qiáng)度密碼生成器:
http://tools.jb51.net/password/CreateStrongPassword
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
python merge、concat合并數(shù)據(jù)集的實(shí)例講解
下面小編就為大家分享一篇python merge、concat合并數(shù)據(jù)集的實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-04-04Python3 獲取文件屬性的方式(時(shí)間、大小等)
這篇文章主要介紹了Python3 獲取文件屬性的方式(時(shí)間、大小等),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-03-03利用python的socket發(fā)送http(s)請(qǐng)求方法示例
這篇文章主要給大家介紹了關(guān)于利用python的socket發(fā)送http(s)請(qǐng)求的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用python具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起看看吧2018-05-05Python實(shí)現(xiàn)識(shí)別手寫(xiě)數(shù)字 Python圖片讀入與處理
這篇文章主要為大家詳細(xì)介紹了Python實(shí)現(xiàn)識(shí)別手寫(xiě)數(shù)字,Python圖片的讀入與處理,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01