python基础教程-生成指定长度的随机数密码

代码如下:

#!/usr/bin/env python# -*- coding:utf-8 -*-

#导入random和string模块import 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) #生成密码 genpwd = ”.join([i for i in slcchar]) return genpwd

if __name__ == ‘__main__’: print genpassword(6)