产生随机数字和字符共同组成的随机码
"""
generate random code
"""
import random
def generate_code(length=1):
all_chars='0123456789abcdefghijklmnopqrstuvwxyzABCEFGHIJKLMNOPQRSTUVWXYZ'
last_pos = len(all_chars)-1
code = ''
for i in range(length):
index = random.randint(0,last_pos)
code += all_chars[index]
return code
l = int(input('please enter the lenth of code: '))
print(generate_code(l))
please enter the lenth of code: 7
VvYHruM
the second solution:
运用chr() 和rangom.randint() 函数同样可以实现
from random import *
def generate_code(length=1):
code = ''
for i in range(length):
a = chr(randint(65, 90))
b = chr(randint(97, 122))
num = str(randint(0, 9))
code += choice([a,b,num])
return code
l = int(input('please enter the lenth of code: '))
print(generate_code(l))
please enter the lenth of code: 6
Kxj6ZQ