random 模块: 用于生成随机数
- '''关于数据类型序列相关, 参照 https://www.cnblogs.com/yyds/p/6123692.html'''
- random()
随机获取 0 到 1 之间的浮点数, 即 0.0 <= num < 1.0
- import random
- # 使用 random 模块, 必须导入
- num = random.random()
- print(num) # 0.0 <= num < 1.0
- randint(m, n)
随机获取 m 到 n 之间的整数, 即 m <= num <= n
- num = random.randint(2, 10)
- print(num) # 2 <= num <= 10, 注意: 是整数
- randrange(start, stop, [step])
随机获取 start 到 stop 之间的整数, 且步长为 step, 默认为 1. 即 start <= num < stop
默认步长时, random.randrange(1, 5) 等价于 random.randint(1, 4)
- # 默认步长
- num = random.randrange(1, 5)
- print(num)
- # 设置步长为 2
- num_step = random.randrange(1, 10, 2)
- # num_step 的取值范围是: 1 到 9 之间的任意一个奇数
- print(num_step)
- shuffle(list)
将列表中的元素顺序打乱, 类似洗牌的操作 (不确定是列表还是可迭代对象, 有误请指正)
- code_list = ['l', 'd', 'e', 'a', 'w', 'e', 'n']
- random.shuffle(code_list) # 返回值为 None, 直接在原列表中操作
- print(code_list)
- choice()
从一个非空序列中随机取出一个元素返回
- code_turple = ('l', 'd', 'e', 'a', 'w', 'e', 'n')
- res = random.choice(code_turple)
- print(res)
以下是一个获取随机验证码的小案例
- '''
- 获取随机验证码小案例
- 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))
来源: https://www.cnblogs.com/xiaodan1040/p/12235316.html