版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liangxy2014/article/details/79263022
前言:
在python中用于生成随机数的模块是random,在使用前需要import
- random.random():生成一个0-1之间的随机浮点数.
- random.uniform(a, b):生成[a,b]之间的浮点数.
- random.randint(a, b):生成[a,b]之间的整数.
- random.randrange(a, b, step):在指定的集合[a,b)中,以step为基数随机取一个数.如random.randrange(0, 20, 2),相当于从[0,2,4,6,…,18]中随机取一个.
- random.choice(sequence):从特定序列中随机取一个元素,这里的序列可以是字符串,列表,元组等,例:
string = 'nice to meet you'
tup = ('nice', 'to', 'meet', 'you')
lst = ['nice', 'to', 'meet', 'you']
print random.choice(string)
print random.choice(tup)
print random.choice(lst) - random.shuffle(lst):将列表中的元素打乱,洗牌
- random.sample(sequence,k):从指定序列在随机抽取定长序列,原始序列不变
string2 = 'nice to meet you'
lst3 = ['nice', 'to', 'meet', 'you']
print random.sample(string2, 2)
print random.sample(lst3, 2)
应用一**洗牌:
import random
lst2 = ['nice', 'to', 'meet', 'you']
# 直接print,会返回为空
# print random.shuffle(lst2)
random.shuffle(lst2)
print lst2
输出结果为:
['you', 'meet', 'nice', 'to']
应用二**生成随机的4位数字验证码:
import random
auth = ''
for i in range(0, 4):
current_code = random.randint(0, 9)
auth += str(current_code)
print auth
应用三**生成随机的4位字母验证码:
auth2 = ''
for ii in range(0, 4):
current_code = random.randint(65, 90)
# ord()函数主要用来返回对应字符的ascii码,
# chr()主要用来表示ascii码对应的字符他的输入时数字
auth2 += chr(current_code)
print auth2
应用四**生成随机的4位字母、数字验证码:
auth3 = ''
for j in range(0, 4):
current = random.randint(0, 4)
if j == current:
current_code = random.randint(0, 9)
else:
current_code = chr(random.randint(65, 90))
auth3 += str(current_code)
print auth3