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-

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

相关文章

Python标准库06之子进程 (subprocess包) 详解

这里的内容以Linux进程基础和Linux文本流为基础。subprocess包主要功能是执行外部的命令和程序。比如说,我需要使用wget下载文件。我在Python中调用wget程序。从这...

Python基类函数的重载与调用实例分析

本文实例讲述了Python基类函数的重载与调用方法。分享给大家供大家参考。具体分析如下: 刚接触Python语言的时间不长,对于这个语言的很多特性并不是很了解,有很多用法都是还不知道。今...

python 公共方法汇总解析

1.计算长度 value = "wangdianchao" # 计算字符个数(长度) number = len(value) print(number) 2.索引取值 valu...

深入理解python中的select模块

简介 Python中的select模块专注于I/O多路复用,提供了select  poll  epoll三个方法(其中后两个在Linux中可用,windows仅支持s...

python连接mysql调用存储过程示例

复制代码 代码如下:#!/usr/bin/env python# -*- coding: utf8 -*-import MySQLdbimport timeimport os, sys,...