有时候我们会想生成一个随机密码,这样我们通过Python中的一些随机方法,就可生成我们任意长度和复杂度的密码,代码如下:
# -*- coding=utf-8 -*- import random import string #多个字符中选取特定数量的字符: print 'rand secret num:' for i in xrange(0,10): print "".join(random.sample('1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()',32)) # 随机整数: print 'rand int :', random.randint(1,1000) # 随机选取0到1000间的偶数: print 'rand even :' ,random.randrange(0, 1000, 2) # 随机浮点数: print 'rand float:',random.random() print 'rand float range:',random.uniform(1, 1000) # 随机字符: print 'rand character:',random.choice('1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()') # 随机选取字符串: print 'rand word:',random.choice(['hello', 'world', 'today','fine']) # 打乱排序 list = [34, 33, 100,3,5,7,8,9,0,6,50]; random.shuffle(list) print "rand order : ", list random.shuffle(list) print "rand order : ", list
执行结果如下:
rand secret num: Of#gobeydiLUJ75zAuD&@n0VTP8Yk9t% ZG^TX&bjlvF%KgUcht@!7#3sYnwV$oQ5 z50)Y%OIVDM6@r(jRJE7k^i*qpUuhwK# AXQniZyIS0&oMj3b$C5W^(4g#w6J@m)c x(d8y9Y4*h)W^&PkU7jEG6cQHN@IOwoA IwuRQhtTNvkH3^O!Es9XZ5qn7Go(p1fm gkflp(*a4EIhQAzJtGM5Km0DWxU#X7BY bDYHtn^M8Ocfp&SJBuLwa$rv!s3XWoVz #vKg4cT5ilr$w@30uC)m*zEoNZf6Xa%k *hV2KCspf1xt$Tb4@3lZ5!DXd0u%6y8E rand int : 808 rand even : 670 rand float: 0.582005578852 rand float range: 11.7565582005 rand character: J rand word: today rand order : [9, 33, 34, 0, 3, 50, 6, 8, 7, 5, 100] rand order : [5, 100, 50, 8, 6, 34, 33, 9, 0, 7, 3]