2.生成验证码
import random def code(number): number_list = [str(i) for i in range(10)] / 生成0 -9 数字列表 litter_list = [chr(i) for i in range(97,123)] / 生成a - z小写字母列表 upper_list = [chr(i) for i in range(65, 91)] / 生成A-Z 大写字母列表 lt = number_list + litter_list +upper_list lt1 = random.sample(lt, number) /从中选取number个验证码
return "".join(lt1)
print(code(4))
random.sample()函数可以选取多个不同的随机数,相当于多次进行random.choice()
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] slice = random.sample(list, 5) # 从list中随机获取5个元素,作为一个片断返回 print slice print list # 原有序列并没有改变
random.choice()每次只能选取一个字符或者元素
print random.choice("学习Python") print random.choice(["JGood", "is", "a", "handsome", "boy"]) print random.choice(("Tuple", "List", "Dict"))