今天做练习的时候碰到这样一个需求:生成随机的5位验证码,以及后续的输入验证,相对后面的验证比较简单,就不赘述了。要求验证码由数字、字母组成,位置不固定。
Ideas:
1. Conversion to the ascii code numbers and letters, used CHR () method
2. ascii code number range is 48-57, 65-90 is uppercase, lowercase is 97-122
3. random function random generating a single range, so consider using two nested random function, generates a first layer three digits 1-3, corresponding to the three ranges, if a judgment of the second layer corresponding to the respective codes, this can be achieved a
4 generates an empty list, the random number into them, after the completion string is connected with the return join
if there is a better idea, god seeking guidance, as follows:
import random
def code():
num=1
code_num=[]
while num <6:
num_ran = random.randint(1, 3)
if num_ran == 1:
a1=chr(random.randint(48,51))
elif num_ran == 2:
a1 = chr(random.randint(65, 90))
else:
a1 = chr(random.randint(97, 122))
code_num.append(a1)
num+=1
return ''.join(code_num)