Python編程生成隨機用戶名及密碼的方法示例
更新時間:2017年05月05日 14:34:52 作者:難免有錯_
這篇文章主要介紹了Python編程生成隨機用戶名及密碼的方法,結合實例形式分析了Python隨機字符串的相關操作技巧,需要的朋友可以參考下
本文實例講述了Python編程生成隨機用戶名及密碼的方法。分享給大家供大家參考,具體如下:
方案一:
import random global 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 "密碼:", 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
常用第二種方法,直觀簡便。
注:(本例在python2.7下測試正常運行。)
PS:這里再為大家提供兩款相關在線工具供大家參考使用:
在線隨機數字/字符串生成工具:
http://tools.jb51.net/aideddesign/suijishu
高強度密碼生成器:
http://tools.jb51.net/password/CreateStrongPassword
希望本文所述對大家Python程序設計有所幫助。
相關文章
利用python的socket發(fā)送http(s)請求方法示例
這篇文章主要給大家介紹了關于利用python的socket發(fā)送http(s)請求的相關資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用python具有一定的參考學習價值,需要的朋友們下面來一起看看吧2018-05-05Python實現(xiàn)識別手寫數字 Python圖片讀入與處理
這篇文章主要為大家詳細介紹了Python實現(xiàn)識別手寫數字,Python圖片的讀入與處理,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-01-01