需求如下:
生成包含數(shù)字盲厌,大小寫和特殊字符的字符串署照,總長度為8,數(shù)字吗浩,大小寫建芙,特殊字符至少都要有一位
代碼如下
import random,string #調(diào)用random、string模塊
def GenPass():
src_digits = string.digits #string_數(shù)字 '0123456789'
src_uppercase = string.ascii_uppercase #string_大寫字母 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
src_lowercase = string.ascii_lowercase #string_小寫字母 'abcdefghijklmnopqrstuvwxyz'
src_special = string.punctuation #string_特殊字符 '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
#sample從序列中選擇n個隨機(jī)獨(dú)立的元素懂扼,返回列表
num = random.sample(src_digits,1) #隨機(jī)取1位數(shù)字
lower = random.sample(src_uppercase,1) #隨機(jī)取1位小寫字母
upper = random.sample(src_lowercase,1) #隨機(jī)取1位大寫字母
special = random.sample(src_special,1) #隨機(jī)取1位大寫字母特殊字符
other = random.sample(string.ascii_letters+string.digits+string.punctuation,4) #隨機(jī)取4位
# 生成字符串
# print(num, lower, upper, special, other)
pwd_list = num + lower + upper + special + other
# shuffle將一個序列中的元素隨機(jī)打亂禁荸,打亂字符串
random.shuffle(pwd_list)
# 列表轉(zhuǎn)字符串
password_str = ''.join(pwd_list)
print(password_str)
GenPass()
生成字符串如下:
dFUJ3?]'
R\1'uC0+
RP*^8n30
隨機(jī)生成中文
python3
import random
print(chr(random.randint(0x4e00,0x9fa5)))
python2
# -*- coding:utf-8 -*-
import random
for i in range(100):
print(unichr(random.randint(0x4e00,0x9fa5)))