python生成隨機驗證碼
阿新 • • 發佈:2018-05-14
python生成隨機密碼 random模塊生成隨機密碼 一、生成隨機驗證碼(純數字及字母加數字):
import random import string checkcod=‘‘ for i in range(5): #5位驗證碼 ‘‘‘ #純數字驗證碼 #隨機值1-9取可以保證5位,如果是1-12就會出現5位以上驗證碼 current=random.randint(1,9) #i數據類型轉換成字符串類型 #checkcod+=str(i) checkcod+=str(current) ‘‘‘ #數字加字母驗證碼 循環5次:猜的值和當前循環i值是否相等 current=random.randrange(0,5) if current == i: #猜的值與當前i循環值相等就會執行下面tmp值為字母 tmp=chr(random.randint(65,90)) #把十進制數字轉換成字母用chr(65到90是獲取大寫字母 #chr(65)是大A chr(90)是大寫 #獲取65到90用random.randint() else: # 否則就是猜的值與當前i值不相等,就會是純數字 tmp=random.randint(0,9) checkcod+=str(tmp) print(checkcod)
二、生成隨機驗證碼(字母加數字):
import random
checkcode = ‘‘
for i in range(4):
current = random.randrange(0,4)
if current != i: #!= 不等於 - 比較兩個對象是否不相等
temp = chr(random.randint(65,90))
else:
temp = random.randint(0,9)
checkcode += str(temp)
print (checkcode)
用!=這個方法獲取的值是字母+數字,而==這個方法是有時循環為數字+字母、有時循環為純數字的。
python生成隨機驗證碼