day5-random
random模块
一、方法介绍
1. random.random() #随机返回[0,1)之间的浮点数
random.uniform(a, b) #随机返回[a,b)之间的浮点数
1 >>> import random 2 >>> random.random() 3 0.6727621440298459 4 >>> random.uniform(1,10) 5 8.840195988094194
2. random.randint(a,b) #随机返回[a,b]之间的整数,包括b
1 >>> random.randint(1,5) 2 1
3. random.randrange(a, b, n) #随机返回[a,b)之间步长为n的整数, 不包括b, a默认为1, n默认为1
1 >>> random.randrange(1, 5, 2) 2 3 3 #随机选取0到100间的偶数 4 >>> random.randrange(0,101,2) 5 68
4. random.choice(序列) #随机返回序列中的值
1 >>> random.choice((1,3,4)) 2 3 3 # 随机字符 4 >>> random.choice('abcdefg&#%^*f') 5 'a' 6 # 随机字符串 7 >>> random.choice(['apple','pear','peach','orange','lemon']) 8 'apple'
5. random.sample(字符串, n) #以列表的形式返回字符串中随机的n个值
1 >>> random.sample('abcdefghij',3) 2 ['c', 'a', 'i']
6. random.shuffle(lst) #对序列或元组进行洗牌
1 >>> items=[1,2,3,4,5,6,7] 2 >>> random.shuffle(items) 3 >>> print items 4 [1, 3, 7, 6, 4, 2, 5]
二、生成随机数
1. 用random和string模块生成随机数
1 >>> import random,string 2 # 拼接小写字符串和数字组成随机原字符串 3 >>> str_source = string.ascii_lowercase + string.digits 4 # 取6个随机字符生成一个随机字符串 5 >>> ''.join(random.sample(str_source,6)) 6 'cbmdri'
2. 生成随机验证码
1 import random 2 checkcode = '' 3 for i in range(4): 4 current = random.randrange(0,4) 5 if current != i: 6 #65-90为大写字母的ascii码 7 temp = chr(random.randint(65,90)) 8 else: 9 temp = random.randint(0,9) 10 checkcode += str(temp) 11 print (checkcode)

浙公网安备 33010602011771号