python 的 random 模块用于生成随机数, 下面介绍一下 random 模块的常用方法:
取随机小数: 数学计算
random.random() 用于生成一个 0-1 的随机浮点数 0<=n<1.0
random.uniform(a,b) 生成一个指定范围内的随机浮点数, a<=n<=b
取随机整数: 彩票 抽奖
random.randint(a,b) 取一个指定范围内的整数 a<=n<=b
random.randrange(start,stop,step) 在指定范围内, 按基数递增的集合内取一个随机数, 如 random.randrange(10,100,2), 结果相当于从 [10,12,14,...98] 序列中获取一个随机数.
从一个序列中随机取值: 抽奖
random.choice() 从序列中随机选择一个返回个数为
random.sample() 从序列中随机选择多个返回, 返回的个数为函数的第二个参数
乱序:
random.shuffle() 打乱一个列表的顺序, 在原列表的基础上直接进行修改, 节省空间
验证码的生成:
6 位数字验证码:
- s = ''
- for i in range(6):
- num = random.randint(0,9)
- s += str(num)
- print(s)
函数版本的:
- def code(n=6):
- s = ''
- for i in range(n):
- num = random.randint(0,9)
- s += str(num)
- return s
- print(code(4))
- print(code())
6 位数字 + 字母验证码:
- def code(n = 6):
- s = ''
- for i in range(n):
- # 生成随机的大写字母, 小写字母, 数字各一个
- num = str(random.randint(0,9))
- alpha_upper = chr(random.randint(65,90))
- alpha_lower = chr(random.randint(97,122))
- res = random.choice([num,alpha_upper,alpha_lower])
- s += res
- return s
- print(code(4))
- print(code())
进阶:
- def code(n = 6,alpha = True):
- s = ''
- for i in range(n):
- num = str(random.randint(0,9))
- if alpha:
- alpha_upper = chr(random.randint(65,90))
- alpha_lower = chr(random.randint(97,122))
- num = random.choice([num,alpha_upper,alpha_lower])
- s += num
- return s
- print(code(4,False))
- print(code(alpha=False))
来源: http://www.bubuko.com/infodetail-2740234.html