random 模块

程序中有很多地方需要用到随机字符,比如登录网站的随机验证码,通过random模块可以很容易生成随机字符串

 

>>> random.randrange(1,10) #返回1-10之间的一个随机数,不包括10
>>> random.randint(1,10) #返回1-10之间的一个随机数,包括10
>>> random.randrange(0, 100, 2) #随机选取0到100间的偶数
>>> random.random()  #返回一个随机浮点数
>>> random.choice('abce3#$@1') #返回一个给定数据集合中的随机字符
'#'
>>> random.sample('abcdefghij',3)  #从多个字符中选取特定数量的字符
['a', 'd', 'b']
#生成随机字符串
>>> import string 
>>> ''.join(random.sample(string.ascii_lowercase + string.digits, 6)) 
'4fvda1'
#洗牌
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> random.shuffle(a)
>>> a
[3, 0, 7, 2, 1, 6, 5, 8, 9, 4]

 

 

 

 

>>> import random
>>> random.randrange(1,10)
2
>>> random.randrange(1,10)
4
>>> random.randrange(1,10)
5
>>> random.randint(1,10)
1
>>> random.randint(1,10)
6
>>> random.randint(1,10)
2

>>> random.random()
0.8246849310781887
>>> random.random()
0.5748257811977814
>>> random.choice('gdafpoqjwpor@$@faopf')
'o'
>>> random.choice('gdafpoqjwpor@$@faopf')
'o'
>>> random.choice('gdafpoqjwpor@$@faopf')
'$'
>>> random.choice('gdafpoqjwpor@$@faopf')
'@'

>>> random.sample('gdafpoqjwpor@$@faopf',5)
['o', 'o', '$', 'j', 'd']
>>> random.sample('gdafpoqjwpor@$@faopf',5)
['a', '@', 'j', 'f', 'o']

#数字0-9
>>> string.digits
'0123456789'

#大小写字母
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

#十六进制
>>> string.hexdigits
'0123456789abcdefABCDEF'

#八进制
>>> string.octdigits
'01234567'

#小写字母
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'

#大写字母
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'

#符号
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

#随机字母数字符串
>>> s = string.ascii_letters + string.digits
>>> random.sample(s,5)
['9', 'm', 'b', 'V', 'R']
>>> ''.join(random.sample(s,5))
'd0mZb'
>>> ''.join(random.sample(s,5))
'bBxTC'
>>> ''.join(random.sample(s,5))
'kz0Zo'

#打乱顺序
>>> d = list(range(20))
>>> d
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> random.shuffle(d)
>>> d
[14, 8, 6, 9, 7, 4, 19, 11, 17, 1, 16, 10, 12, 13, 15, 18, 5, 3, 2, 0]

 

posted @ 2018-05-12 10:48  元贞  阅读(180)  评论(0编辑  收藏  举报