random模块的常用函数
import random print(random.random()) #获得0-1之间的随机浮点数 print(random.randint(1,3)) #生成[1,3]的整数 print(random.randrange(1,3)) #顾头不顾尾 print(random.choice([1,2,3,4,5,6])) #参数可以是任意序列类型,返回序列中的一个值 print(random.sample([1,2,3,4,5,6],2)) #同上,但随机取两个元素以列表形式返回 print(random.sample("abcdefghijklm",2)) print(random.sample(('z','x','y','m','n'),2)) print(random.uniform(1,3)) #生成1~3的随机浮点数 test=[1,2,3,4,5,6,7] random.shuffle(test) #打乱次序 参数不能是元组 print(test)
验证码例子
#4位验证码(包含数字,大小写字母) checkcode='' for i in range(4): cur=random.randrange(0,4) if i==cur: cur=random.randint(0,9) elif cur==1: cur=chr(random.randint(65,90)) else: cur=chr(random.randint(97,122)) checkcode+=str(cur) print(checkcode)