程序中有不少地方須要用到隨機字符,好比登陸網站的隨機驗證碼,python中經過random模塊能夠很容易生成隨機字符串。python
實例:大樂透,公司年會抽獎git
>>> import random >>> random.randint(1,100) #1-100中間取一個隨機數,包含100 32 >>> random.randint(1,100) 59 >>> random.randint(1,100) 32 >>>random.randrange(1-100) #1-100中間取一個隨機數,不包含100 22 >>>random.choice('da124#!') #從字符串裏返回隨機的東西,拼隨機驗證碼可能用的到 '4' >>>random.sample('da124#!',3) #返回3個隨機值 ['#', '4', '1'] >>> import string >>> string.digits '0123456789' >>> string.ascii_letters 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' 把小寫字母和大寫字母都顯示出來 >>> string.hexdigits '0123456789abcdefABCDEF' >>> s = string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation >>>s 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' >>>random.sample(s, 5) ['q', 'h', 'L', 'O', 'S'] >>>random.sample(s, 5) ['B', '3', 'J', 'Y', '7'] >>>''.join(random.sample(s,5)) 'VGN:R' # 隨機驗證碼 #洗牌 >>> d = list(range(0,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 [9, 38, 62, 53, 80, 78, 52, 95, 20, 65, 30, 64, 71, 92, 81, 4, 69, 37, 34, 11, 35, 84, 36, 44, 76, 98, 13, 1, 43, 55, 79, 63, 17, 12, 77, 26, 5, 61, 94, 27, 0, 58, 83, 72, 49, 25, 59, 60, 2, 41, 89, 23, 82, 97, 90, 54, 99, 6, 3, 93, 73, 70, 96, 10, 40, 45, 67, 8, 16, 21, 39, 85, 31, 50, 48, 47, 46, 7, 14, 51, 18, 87, 66, 75, 19, 88, 56, 68, 57, 32, 33, 24, 74, 28, 42, 15, 91, 86, 22, 29]