程序中有很多地方需要用到随机字符,比如登陆网站的随机验证码,通过random模块可以很容易生成随机字符串。
>>> import random >>> random.randint(1,100) #在1-100之间生成一个随机数 3 >>> random.randrange(1,100) #在1-99之间生成一个随机数 10 >>> random.random() #返回一个浮点数 0.9143138919444751 >>> random.choice('asdfrv1234') #在字符串里随机返回字符串中的一个元素 'f' >>> random.sample('asdfrv1234',3) #在给定字符串里随机返回多个元素 ['d', '3', '4'] >>> import string >>> string.digits #返回所有的数字 '0123456789' >>> string.ascii_letters #返回所有的大小写字母 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> string.hexdigits #返回所有的16进制 '0123456789abcdefABCDEF' >>> string.octdigits #返回所有的8进制 '01234567' >>> string.ascii_lowercase #返回所有小写字母 'abcdefghijklmnopqrstuvwxyz' >>> string.ascii_uppercase #返回所有大写字母 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> string.punctuation #返回所有特殊字符 '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' >>> string.ascii_uppercase + string.digits #返回所有的大写字母加数字 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' #生成随机验证码 >>> s = string.ascii_uppercase + string.digits >>> random.sample(s,5) ['P', '3', '1', 'T', '2'] >>> ''.join(random.sample(s,5)) '4CQT0' #打乱 >>> d = list(range(100)) >>> d [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99] >>> random.shuffle(d) #打乱 >>> d [95, 43, 89, 45, 64, 38, 56, 40, 80, 92, 60, 73, 35, 87, 52, 88, 34, 31, 71, 81, 0, 51, 32, 75, 30, 26, 12, 77, 91, 42, 48, 36, 28, 22, 9, 46, 44, 15, 84, 66, 14, 97, 19, 62, 33, 21, 47, 65, 82, 57, 24, 99, 39, 61, 85, 29, 69, 86, 70, 78, 17, 4, 79, 25, 50, 11, 53, 37, 83, 68, 16, 23, 72, 74, 94, 2, 27, 41, 54, 98, 96, 3, 63, 13, 76, 5, 10, 58, 59, 1, 67, 20, 7, 49, 55, 18, 8, 90, 6, 93]