脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python 中random模块的常用方法总结

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

2020-11-24 00:45bigberg Python

这篇文章主要介绍了python 中random的常用方法总结的相关资料,需要的朋友可以参考下

pythonrandom的常用方法总结

一、random常用模块

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

?
1
2
3
4
print(random.random())
 
# 输出
0.6060562117996784

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

?
1
2
3
4
5
print(random.randint(1, 5))
 
#输出
 
5

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

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

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

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

二、string 模块

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

?
1
2
3
4
5
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  #特殊字符

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

2.6 生成一个随机验证码

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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-

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

原文链接:http://www.cnblogs.com/bigberg/p/6869357.html

延伸 · 阅读

精彩推荐