Random模块:
>>> import random
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_BuiltinMethodType',
'_MethodType', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_inst', '_itertools', '_log', '_pi', '_random',
'_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate',
'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random',
'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
>>> random.choice("abcdef")
'c'
>>> random.choice([1,2,3,4,5,6,7,8,9])
8
>>> random.randint(0, 9) # 包含9
3
>>> random.randint(0, 9)
9
>>> random.randrange(0,3) # 不包含3
1
>>> random.randrange(0,3)
0
>>> random.sample("abcdefg", 3) # 从列表中随机选择3 个组成列表
['e', 'b', 'd']
>>> random.random() # 随机从0到1 之间选择一个浮点数,且不接受参数,只能在0到1之间
0.5100862728498153
>>> random.uniform(1,3) # 随机从1,到3之间选择一个浮点数,可接受参数
1.26761769366796
>>> random.uniform(1,3)
2.792811152671068
>>> random.uniform(1,3)
2.8292418788592224
>>> a = [1,2,3,4,5,6]
>>> random.shuffle(a) # 洗牌功能,将列表重排,打乱顺序
>>> a
[5, 2, 3, 6, 1, 4]
应用实例:
'''写一个随机生成验证码的函数'''
import random
import string
chr_num = ' '
for i in range(5):
str_num = str(random.choice(string.ascii_lowercase + string.digits))
chr_num += str_num
print(chr_num)
string模块:
>>> import string
>>> dir(string)
['Formatter', 'Template', '_ChainMap', '_TemplateMetaclass', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_re', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace']
>>> string.ascii_letters()
Traceback (most recent call last):
File "", line 1, in
string.ascii_letters()
TypeError: 'str' object is not callable
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.capwords
>>> string.digits
'0123456789'
>>> string.hexdigits
'0123456789abcdefABCDEF'
>>> string.octdigits
'01234567'
>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.whitespace
' \t\n\r\x0b\x0c'
>>>