random模塊

1、簡述

  咱們常常會使用一些隨機數,或者須要寫一些隨機數的代碼,今天咱們就來整理隨機數模塊:random模塊git

2、random模塊

一、random.random()dom

功能:隨機返回一個小數oop

>>> import random
>>> random.random()
0.14090974546903268  #隨機返回一個小數

二、random.randint(a,b)spa

功能:隨機返回a到b之間任意一個數,包括bcode

>>> import random
>>> random.randint(1,5)
5   #能夠返回5
>>> random.randint(1,5)
2

三、random.randrange(start, stop=None, step=1)blog

功能:隨機返回start到stop,可是不包括stop值ci

>>> import random
>>> random.randrange(5)  #不能隨機返回5
4
>>> random.randrange(5)
1

四、random.sample(population, k)字符串

功能:從population中隨機獲取k個值,以列表的形式返回string

>>> import random
>>> random.sample(range(10),3)  #從0-9返回3個隨機數
[3, 1, 0]
>>> random.sample('abcdefghi',3)  #從'abcdefghi'中返回3個字符
['a', 'h', 'b']

3、string模塊

一、string.ascii_lettersit

功能:返回大小寫字母的字符串

>>> import string
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'  #返回大小寫字母字符串

二、string.ascii_lowercase

功能:返回小寫字母的字符串

>>> import string
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'  #返回小寫字母的字符串

三、string.ascii_uppercase

功能:返回大寫字母的字符串

>>> import string
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'  #返回大寫字母的字符串

4string.digits

功能:返回0-9數字的字符串

>>> import string
>>> string.digits
'0123456789'    #返回0-9數字的字符串

五、string.punctuation

功能:返回全部特殊字符,並以字符串形式返回

>>> import string
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'  #返回全部特殊字符,並以字符串的形式返回

4、生成隨機數

一、用random和string模塊生成隨機數

>>> import random,string
>>> str_source = string.ascii_lowercase + string.digits  #大寫字母字符和0-9數字字符串拼接
>>> random.sample(str_source,6)    #取6個隨機字符
['f', '1', 'a', 'm', 'j', 'h']
>>> ''.join(random.sample(str_source,6))  #生成一個隨機數字符串
'f84bsj'

二、程序實現

import random
checkcode = ''
for i in range(4):
    current = random.randrange(0,4)
    if current != i:   #若是當前的loop  i不等於隨機數,就取出65-90中的隨機字符
        temp = chr(random.randint(65,90))
    else:
        temp = random.randint(0,9)
    checkcode += str(temp)
print(checkcode)
相關文章
相關標籤/搜索