模块 random

random 模块

import random
# 随机小数
random.random() # 大于0且小于1之间的小数
# 0.6860937326862173
random.uniform(1,3) # 大于1小于3直接的小数
# 2.3627834021598133

# 随机整数
random.randint(1,5) # 大于等于1小于等于5之间的整数
# 1
random.randrange(1,10,2) # 大于等于1小于10之间的奇数
# 7

# 随机返回一个
random.choice([1,'23',[1,2,3]]) # 1或者23或者[1,2,3]
# 23
# 随机返回多个
random.sample([1,2,3,'23',[4,5,6]],3) # 列表中任意3个元素的组合
# [3, 1, [4, 5, 6]]

# 打乱列表顺序
l = [1,2,3,4,5]
random.shuffle(l) # 打乱次序
print(l)
# [4, 5, 3, 1, 2]

随机生成验证码

def get_code(n):
    code = ''
    for i in range(n):
        num = str(random.randint(0,9))
        upper_letter = chr(random.randint(65,90))
        lower_letter = chr(random.randint(97,122))
        code += random.choice([num,upper_letter,lower_letter])
    return code
res = get_code(6)
print(res)
# okULb3
千里之行,始于足下。
原文地址:https://www.cnblogs.com/jincoco/p/11329616.html