Python-随机模块-random
Posted 北门吹雪
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python-随机模块-random相关的知识,希望对你有一定的参考价值。
random
生成随机变量
生成 [0, 1) 随机数 .random
import random
random_number = random.random()
print(random_number)
print(random_number + 1)
生成[start, end] 随机数 .uniform
import random
random_number = random.uniform(0, 10)
print(random_number)
生成 [start, end] 区间随机整数 .randint
import random
random_number = random.randint(1, 10)
print(random_number)
生成 (start, end) 区间随机整数 randrange
import random
random_number = random.randrange(1, 10)
print(random_number)
从序列中随机取一个值 choice
import random
random_sequence = random.choice(["1", "2", "3"])
print(random_sequence)
从序列中随机取样 sample
import random
target_str = "0123456789abcdefghijklmnopqrstuvwxyz"
random_sequence = random.sample(target_str, 6)
print(random_sequence)
# 6位数随机验证码
print(‘‘.join(random_sequence))
算数运算验证码实现
import random number_str = "123456789" letter_str = ‘abcdefghijklmnopqrstuvwxyz‘ operator = "+-×" random_str = random.choice(number_str) + random.choice(operator) + random.choice(number_str) + random.choice(operator) + random.choice(number_str) print(random_str.replace(‘ב, ‘*‘)) print(eval(random_str.replace(‘ב, ‘*‘)))
以上是关于Python-随机模块-random的主要内容,如果未能解决你的问题,请参考以下文章