python內建模組--random

來源:互聯網
上載者:User

標籤:python、random

random模組                                                                                                                                                 

    random顧名思義,用於產生隨機字串,具體用法如下

import randomlis = [1,2,3,4,5,6,7,8,9,10]#隨機產生浮點數print(random.random())          #隨機返回0~1之間的浮點數print(random.uniform(1,10))     #隨機返回1~10之間的浮點數#隨機產生整數print(random.randint(1,10))         #隨機產生1~10之間的整數print(random.randrange(0,10,2))     #隨機產生0~10之間的偶數print(random.randrange(1,10,2))     #隨機產生1~10之間的基數#操作序列、字串##從序列、字串中隨機返回一個元素print(random.choice(lis))print(random.choice('abcdefg'))##隨機截取序列、字串中指定長度片段print(random.sample(lis,2))print(random.sample('abcdefg',2))##打亂一個序列random.shuffle(lis)print(lis)

列印結果如下:

0.476266933939917374.08444480427172258814g[9, 4]['f', 'a'][7, 6, 1, 2, 10, 3, 4, 8, 5, 9]

例子:

#-*- coding:utf-8 -*-#隨機密碼產生器,必須含有大小寫字母、數字和符號'''(ASCII碼)數字:[48,57]小寫字母:[97,122]大寫字母:[65,90]符號:[33,47]'''import randompass_num = int(input("請輸入密碼長度:"))my_num = pass_num-4mast_list = []      #用於隨機收集大小寫字母、數字和符號的ASCII碼各一個ascii_list = []     #用於隨機收集剩下的密碼字元對應的ASCII碼passwd_list = []    #用於收集由ASCII碼轉換後的字元number = range(48,58)s_letter = range(97,123)b_letter = range(65,91)symbol = range(35,38)def creat_mast(lis):    a = random.choice(lis)    mast_list.append(a)creat_mast(number)creat_mast(s_letter)creat_mast(b_letter)creat_mast(symbol)random.shuffle(mast_list)def creat_list(lis):    for i in lis:        ascii_list.append(i)creat_list(number)creat_list(s_letter)creat_list(b_letter)creat_list(symbol)ascii_list = random.sample(ascii_list,my_num) + mast_listfor i in ascii_list:    a = chr(i)    passwd_list.append(a)my_pass = "".join(passwd_list)print('隨機密碼為:%s'%(my_pass))


python內建模組--random

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.