方法一,大小寫字母+數字:
import random
import string
ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 8))
print ran_str
方法二,大小寫字母+數字+特殊字符:
應用python random標準庫做一個隨機生成密碼的程序,可以隨機生成任意多個字符。(基于python2.7,如果是python3需要修改下)
#-*-coding:utf-8 -*-
#author:wangxing
import random
import string
import sys
#存儲大小寫字母和數字,特殊字符列表
STR = [chr(i) for i in range(65,91)] #65-91對應字符A-Z
str = [chr(i) for i in range(97,123)] #a-z
number = [chr(i) for i in range(48,58)] #0-9
#特殊字符串列表獲取有點不同
initspecial = string.punctuation #這個函數獲取到全部特殊字符,結果為字符串形式
special = [] #定義一個空列表
#制作特殊符號列表
for i in initspecial:
special.append(i)
total = STR + str + number + special
#print total
choices = ['6','8','10','16']
def Randompassword(your_choice):
if your_choice in choices:
passwordli = random.sample(total,int(your_choice)) ##sample函數作用是取幾個列表里的值并返回一個新列表,此處得到的是列表需要轉換為字符串顯示出來
passwordst = ''.join(passwordli) #現在得到的是轉換后的字符串 ‘’是分隔符,里面可以為; : . 等等
print "\033[32m生成的\033[0m" + your_choice + "\033[32m位數密碼為:\033[0m\n" + passwordst
else:
print "\033[31m請輸入指定位數(6,8,10,16) \033[0m"
if __name__ == '__main__':
while True:
choice = raw_input("\033[33m請輸入你要得到隨機密碼的位數:(6,8,10,16),或輸入q退出\033[0m\n")
if choice != 'q': #輸入q則退出循環
Randompassword(choice) #執行函數
else:
break
方法三,字母+數字:
#!/usr/bin/env python
# -*- coding=utf-8 -*-
import random, string #導入random和string模塊
def GenPassword(length):
#隨機出數字的個數
numOfNum = random.randint(1,length-1)
numOfLetter = length - numOfNum
#選中numOfNum個數字
slcNum = [random.choice(string.digits) for i in range(numOfNum)]
#選中numOfLetter個字母
slcLetter = [random.choice(string.ascii_letters) for i in range(numOfLetter)]
#打亂組合
slcChar = slcNum + slcLetter
random.shuffle(slcChar)
#生成隨機密碼
getPwd = ''.join([i for i in slcChar])
return getPwd
if __name__ == '__main__':
print GenPassword(6)
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
