random模块
应用方法:
1 #!/usr/bin/env python 2 # encoding: utf-8 3 import random 4 import string 5 #随机整数: 6 print( random.randint(0,100)) #0—99之间的整数 7 8 #随机选取0到100间的偶数: 9 print(random.randrange(0, 101, 2)) 10 11 #随机浮点数: 12 print( random.random()) #0.2746445568079129 13 print(random.uniform(1, 10)) #9.887001463194844 14 15 #随机字符: 16 print(random.choice('abcdefg&#%^*f')) #随机选取一个字符 17 18 #多个字符中选取特定数量的字符: 19 print(random.sample('abcdefghij',3)) #['f', 'h', 'd'] 参数3 选取三个 20 21 #随机选取字符串: 22 print( random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )) #apple 23 24 #洗牌# 25 items = [1,2,3,4,5,6,7] 26 print(items) #[1, 2, 3, 4, 5, 6, 7] 27 random.shuffle(items) 28 print(items) #[1, 4, 7, 2, 5, 3, 6]
生成随机验证码:
1 import random 2 checkcode = '' 3 for i in range(4): 4 current = random.randrange(0,4) 5 if current != i: 6 temp = chr(random.randint(65,90)) 7 else: 8 temp = random.randint(0,9) 9 checkcode += str(temp) 10 print (checkcode)