import random # 随机数
import string
随机小数
print(random.random()) 0.8681861054821751
在1-5范围 随机打印
print(random.randint(1,5)) 1
和randint区别 在1-4范围 随机打印
print(random.randrange(1,5)) 3
在这个范围内 随机拿出5个数出来,以list方式打印
print(random.sample(range(100),5)) [50, 92, 29, 94, 30] print(random.sample(‘abcdef‘,5)) [‘b‘, ‘d‘, ‘f‘, ‘e‘, ‘c‘]
打印0-9数字
print(string.digits) 0123456789
打印a-z
print(string.ascii_letters) abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
随机拿出0-9 a-z A-Z 里面随机数 以字符串格式打印
str_source = string.ascii_letters + string.digits print(‘‘.join(random.sample(str_source,5))) Dzn5w
choice 随机传递序列元祖,字符串,列表 里面随机数
print(random.choice([1,3,5])) 5 print(random.choice(‘helo‘)) e
洗牌功能
l = [1,2,3,4,5,6,7,8] print(l) [1, 2, 3, 4, 5, 6, 7, 8] random.shuffle(l) print(l) [6, 2, 5, 3, 4, 8, 1, 7]
随机数验证码小程序
import random checkcode = ‘‘ for i in range(5): current = random.randrange(0,5) if current != i: temp = chr(random.randint(65,90)) elif i > 2: temp = chr(random.randint(97,122)) else: temp = random.randint(0,9) checkcode += str(temp) print(checkcode)