生成随机手机号码和密码,手机号码要求‘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) #数字字符串