'''关于数据类型序列相关,参照https://www.cnblogs.com/yyds/p/6123692.html'''
随机获取0 到1 之间的浮点数,即 0.0 <= num < 1.0html
import random # 使用random模块,必须导入 num = random.random() print(num) # 0.0 <= num < 1.0
随机获取m 到n 之间的整数,即m <= num <= npython
num = random.randint(2, 10) print(num) # 2 <= num <= 10, 注意:是整数
随机获取start 到stop之间的整数,且步长为step,默认为1。即start <= num < stopdom
默认步长时,random.randrange(1, 5) 等价于 random.randint(1, 4)code
# 默认步长 num = random.randrange(1, 5) print(num) # 设置步长为2 num_step = random.randrange(1, 10, 2) # num_step的取值范围是:1到9之间的任意一个奇数 print(num_step)
将列表中的元素顺序打乱,相似洗牌的操做(不肯定是列表仍是可迭代对象,有误请指正)htm
code_list = ['l', 'd', 'e', 'a', 'w', 'e', 'n'] random.shuffle(code_list) # 返回值为None,直接在原列表中操做 print(code_list)
从一个非空序列中随机取出一个元素返回对象
code_turple = ('l', 'd', 'e', 'a', 'w', 'e', 'n') res = random.choice(code_turple) print(res)
如下是一个获取随机验证码的小案例blog
''' 获取随机验证码小案例 chr(int(n)):用于将ASCⅡ码的数值转换成对应的字符,n的取值范围在0~255,返回值为字符串类型 ord(str('a')):用于将单字符字符串转换成对应的ASCⅡ码,返回值为整型 在ASCⅡ码中,数值65-90:大写英文字符;数值97-122:小写英文字符 ''' def get_code(n): '''n:生成几位的验证码''' code = '' for line in range(n): # 随机获取任意一个小写字符的ASCⅡ码 l_code = random.randint(97, 122) # 将ASCⅡ码转换成对应的字符 l_code = chr(l_code) # 随机获取任意一个大写字符的ASCⅡ码 u_code = random.randint(65, 90) # 将ASCⅡ码转换成对应的字符 u_code = chr(u_code) # 随机获取任意一个0-9之间的数字 n_code = random.randint(0, 9) # 将上述3个随机字符存储起来 code_list = [l_code, u_code, n_code] # 从列表中任意取出一个 random_code = random.choice(code_list) # 将字符拼接起来 code += str(random_code) return code print(get_code(5))