Python random string模块

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 "<pyshell#145>", line 1, in <module>
    string.ascii_letters()
TypeError: 'str' object is not callable
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.capwords
<function capwords at 0x00000000028C37B8>
>>> 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'
>>> 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值