python 中random模块的常用方法总结

yipeiwu_com6年前Python基础

python 中random的常用方法总结

一、random常用模块

1.random.random() 随机生成一个小数

print(random.random())
 
# 输出
0.6060562117996784

2.random.randint(m,n) 随机生成一个m到n的整数(包括n)

print(random.randint(1, 5))
 
#输出
 
5

3. random.randrange(m,n) 随机生成m到n中的一个数,包括 m 但是不包括 n

print(random.randrange(1, 5))
 
# 输出
 
3

4. random.smaple(source,n) 在 source 中随机找出n个值,生成一个列表

print(random.sample(range(100), 5))
 
#输出
[27, 49, 21, 81, 45]

二、string 模块

 2.1 string.ascii_letters   # 所有的大小写英文字母

letters = string.ascii_letters
print(letters)
 
# 输出
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

2.2 string.ascii_lowercase # 所有的小写字母

2.3 string.ascii_uppercase # 所有的大写字母

2.4 string.digit # 1-9

2.5 string.punctuation  #特殊字符

sss = string.punctuation
print(sss)
 
# 输出
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
  

2.6 生成一个随机验证码

我们利用random和string模块模拟生成一个包含特殊字符以及大小写的验证码

import random
import string
 
str_source = {
 1: string.ascii_lowercase,
 2: string.ascii_uppercase,
 3: string.digits,
 4: string.punctuation
}
 
check = []
 
for i in range(1, 5):
  y = random.sample(str_source[i], 1)
  check.append(y[0])
 
print("".join(check))
 
# 输出
bV5-

 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

pytorch模型预测结果与ndarray互转方式

预测结果转为numpy: logits=model(feature) #如果模型是跑在GPU上 result=logits.data.cpu().numpy() / logi...

Python 调用 Windows API COM 新法

Python中调用Win32API 通常都是使用 PyWin32或者ctypes。但要么依赖文件较多,要么用法繁琐。 这里介绍在Python中调用Win32 API 或者COM组件的另一...

Python 中Django验证码功能的实现代码

Python 中Django验证码功能的实现代码

  为了防止机器人频繁登陆网站或者破坏分子恶意登陆,很多用户登录和注册系统都提供了图形验证码功能。   验证码(CAPTCHA)是“Completely Automated Public...

Python随手笔记第一篇(2)之初识列表和元组

Python随手笔记第一篇(2)之初识列表和元组

Python中,列表和元组是一种数据结构:序列,序列中的每个元素都被分配一个序号,元素的位置,第一原元素的位置为0,因此类推。序列是最基本的数据结构,列表和元组他们之间具有一定的区别,即...

Django框架模板用法入门教程

本文实例讲述了Django框架模板用法。分享给大家供大家参考,具体如下: Django 模板标签 if/else 标签 基本语法格式如下: {% if condition %}...