Summary of common methods of random module in python
- 2020-06-12 09:34:03
- OfStack
Summary of common random methods in python
1. Common random modules
1.random.random() generates 1 decimal at random
print(random.random())
# The output
0.6060562117996784
2.random.randint(m,n) randomly generate 1 integer from m to n (including n)
print(random.randint(1, 5))
# The output
5
3. random.randrange(m,n) randomly generates 1 number from m to n, including m but excluding n
print(random.randrange(1, 5))
# The output
3
4. random.smaple(source,n) randomly found n values in source to generate a list
print(random.sample(range(100), 5))
# The output
[27, 49, 21, 81, 45]
2. string module
2.1 string. ascii_letters # all upper and lower case letters
letters = string.ascii_letters
print(letters)
# The output
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
All lowercase letters of ES52en. ascii_lowercase #
2.3 string. ascii_uppercase # all capital letters
2.4 string.digit # 1-9
2.5 string. punctuation # special characters
sss = string.punctuation
print(sss)
# The output
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
2.6 Generate a random verification code
We use random and string modules to simulate the generation of a captcha containing special characters and case
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))
# The output
bV5-
Thank you for reading, I hope to help you, thank you for your support to this site!