random模組,pythonrandom模組

來源:互聯網
上載者:User

random模組,pythonrandom模組

一、random常用模組

1.random.random() 隨機產生一個小數

print(random.random())# 輸出0.6060562117996784

 

2.random.randint(m,n) 隨機產生一個m到n的整數(包括n)

print(random.randint(1, 5))#輸出5

 

3. random.randrange(m,n) 隨機產生m到n中的一個數,包括 m 但是不包括 n

print(random.randrange(1, 5))# 輸出3

 

4. random.smaple(source,n) 在 source 中隨機找出n個值,產生一個列表

print(random.sample(range(100), 5))#輸出[27, 49, 21, 81, 45]

 

二、string 模組

 2.1 string.ascii_letters   # 所有的大小寫英文字母

letters = string.ascii_lettersprint(letters)# 輸出abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

  

2.2 string.ascii_lowercase # 所有的小寫字母

2.3 string.ascii_uppercase # 所有的大寫字母

 

2.4 string.digit # 1-9

 

2.5 string.punctuation  #特殊字元

sss = string.punctuationprint(sss)# 輸出!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

  

2.6 產生一個隨機驗證碼

我們利用random和string模組類比產生一個包含特殊字元以及大小寫驗證碼

import randomimport stringstr_source = { 1: string.ascii_lowercase, 2: string.ascii_uppercase, 3: string.digits, 4: string.punctuation}check = []for i in range(1, 5):    y = random.sample(str_source[i], 1)    check.append(y[0])print("".join(check))# 輸出bV5-

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.