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]總結
- 上一篇: re 模块
- 下一篇: 文件copy模块shutil