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

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