python--random模块(产生随机值)、洗牌、验证码应用
2018-02-05 18:27
501 查看
前言:
在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):从特定序列中随机取一个元素,这里的序列可以是字符串,列表,元组等,例:
random.shuffle(lst):将列表中的元素打乱,洗牌
random.sample(sequence,k):从指定序列在随机抽取定长序列,原始序列不变
应用一**洗牌:
应用二**生成随机的4位数字验证码:
应用三**生成随机的4位字母验证码:
应用四**生成随机的4位字母、数字验证码:
在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
相关文章推荐
- day04_python random模块随机生成验证码
- [ Python - 5 ] 通过random模块生成随机字符串
- python(5)–random模块及验证码
- Python随机生成数模块random使用实例
- Oracle之 【RANDOM】使用dbms_random.string产生随机字符串的用法及应用
- python 利用random的shuffle洗牌方法生产1个12位数的随机密码
- python中random模块基础用法(利用random生成验证码)
- Python3基础 random 产生指定区间的随机整数
- Python random模块(随机整数部分内容)
- Python random模块sample、randint、shuffle、choice随机函数概念和应用
- python——random模块的应用
- python在图片写文字,产生随机验证码序列号
- Python使用PIL模块生成随机验证码
- python PIL模块与随机生成中文验证码
- python中random模块产生随意行走的路线
- python PIL模块与随机生成中文验证码
- Python实现简单生成验证码功能【基于random模块】
- 从数组中返回随机元素(python中的random模块的使用)
- Python的random模块
- Python模块学习 ---- random 随机数生成