生成隨機手機號碼和密碼


生成隨機手機號碼和密碼,手機號碼要求‘1’開頭,密碼由字母和數字組成

 

生成手機號和取到所有字母,數字:

 1 import random
 2 
 3 phone_number = ['1']
 4 for i in range(0,10):
 5     j = str(random.randint(0,9))
 6     phone_number.append(j)
 7 phone = ''.join(phone_number)       #join用法,join有返回值,返回插入后的字符串,要用一個變量接收返回值才能調用
 8 print(phone)
 9 
10 list1 = [i for i in range(48,58)]       #數字對應ascii碼
11 list2 = [i for i in range(65,91)]       #大寫字母對應ascii碼
12 list3 = [i for i in range(97,123)]      #小寫字母對應ascii碼

生成隨機密碼方法一:

  隨機從三個列表隨機取值,取十次,值添加到passwd列表。輸出是用join把列表轉化為字符串

 1 passwd = []
 2 i = 0
 3 while i < 10:
 4     j = random.randint(1,3)
 5     if j == 1:
 6         num = random.choice(list1)
 7         passwd.append(chr(num))
 8     elif j == 2:
 9         upper = random.choice(list2)
10         passwd.append(chr(upper))
11     elif j == 3:
12         lower = random.choice(list3)
13         passwd.append(chr(lower))
14     i += 1
15 print(''.join(passwd))

生成隨機密碼方法二:

1 # 方法二
2 list4 = [ chr(i) for i in list1 + list2 + list3]
3 passwd = random.sample(list4,10)        #sample()可以隨機取多個,但是不會重復,密碼可以重復字符串,choice()只能選一個
4 print(passwd)

生成隨機密碼方法三:

  用以下語法可重復隨機選十次

1 # # 方法三     #循環choice()
2 list4 = [ chr(i) for i in list1 + list2 + list3]
3 # need=[random.randint(0,100) for _ in range(要取出的數據條數)]     #可重復隨機取出列表多個元素
4 passwd = [random.choice(list4) for i in range(10)]          #choice()后面的內容是循環choice()的次數
5 print(passwd)
6 print(''.join(passwd))

 也可以用Python封裝好的東西直接獲得數字,小寫,大寫字母字符串,再從這些字符串里choice

1 import string
2 
3 print(string.ascii_letters)     #string類型,大寫加小寫字母字符串
4 print(string.ascii_lowercase)   #小寫字母字符串
5 print(string.ascii_uppercase)   #大寫字母字符串
6 print(string.digits)            #數字字符串

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM