python模块之random

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

 

import random

# 取随机数

print(random.randint(1, 100))  # 从1到1000之间取一个随机数,数字自定义
print(random.randrange(1, 100))  # 和ranint的区别是这个不包含100,ranint包含

# 随机浮点数
print(random.random())  # 0.5214745826531983

# 返回一个指定数据结构的随机字符。做随机验证码的时候用得到

print(random.choice('asdasd!()&&^%&%$jakshds12313'))  # &

print(random.sample('asdasd!()&&^%&%$jakshds12313', 3))  # 返回多个,以列表的形式返回  ['a', '%', '&']

# 可以用string找生成随机验证码的数据源

import string

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

s = string.ascii_lowercase + string.digits
check_code = ''.join(random.sample(s, 5))
print(check_code)  # g7fuw

# 洗牌

d = list(range(100))
random.shuffle(d)
print(d)  # 乱序了

 

posted @ 2018-11-21 18:09  梁少华  阅读(246)  评论(0编辑  收藏  举报