本文實例講述了Python編程生成隨機用戶名及密碼的方法。分享給大家供大家參考,具體如下:
方案一:
import randomglobal userName,userPassword #為了便于使用,定義為全局變量userName = ''userPassword = ''def get_userNameAndPassword():  global userName, userPassword  usableName_char = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+=-><:}{?/" #可作為用戶名的字符  usablePassword_char ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_.1234567890" #可作為密碼的字符,根據所需可適當增減  e_userName = [] #定義一個臨時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 "密碼:", userPasswordexcept 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-8import randomglobal 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 "密碼:", userPasswordexcept Exception, e:  print e.reason程序輸出:
用戶名: GweV?2um密碼: fwiOZL
常用第二種方法,直觀簡便。
注:(本例在python2.7下測試正常運行。)
PS:這里再為大家提供兩款相關在線工具供大家參考使用:
在線隨機數字/字符串生成工具:
http://tools.jb51.net/aideddesign/suijishu
高強度密碼生成器:
http://tools.jb51.net/password/CreateStrongPassword
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python數據結構與算法教程》、《Python Socket編程技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答