python实现生成身份证函数

首先,先简单的介绍一下身份证号码组成规则

前1、2位数字表示:所在省(直辖市、自治区)的代码;

第3、4位数字表示:所在地级市(自治州)的代码

第5、6位数字表示:所在区(县、自治县、县级市)的代码;

第7—14位数字表示:出生年、月、日;

第15、16位数字表示:所在地的派出所的代码;

第17位数字表示性别:奇数表示男性,偶数表示女性;

第18位数字是校检码

下面上代码:

 1 import time
 2 import random
 3 #获取六位城市信息号码
 4 d_1={'山东青岛':'370102','山西晋城':'140502'}
 5 def day_age(age,birthday=None,gender=1):
 6     id_code_list=[7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]#身份证每一位对应系数
 7     check_code_list=[1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2] #余数的对应数字
 8     te = time.localtime(time.time())
 9     year=time.strftime('%Y',te)
10     if not birthday:
11         birthday = time.strftime('%m%d', te)
12     year = str(int(year)-int(age))
13     #获取三位顺序码
14     sequence_code = random.randrange(0, 999)
15     #gender==1表示男性
16     if gender ==1:
17         sequence_code=sequence_code if sequence_code %2!= 0 else sequence_code-1
18     else:
19         sequence_code = sequence_code if sequence_code % 2 == 0 else sequence_code - 1
20     #str.zfill(width):width--原字符串右对齐,前面填充0
21     id_code =d_1['山东青岛']+year+birthday+str(sequence_code).zfill(3)
22     #获取最后一位校验码
23     verify_code =check_code_list[sum(x*y for x,y in zip([x for x in id_code_list],[int(y) for y in id_code]))%11]
24     # sum=0
25     # for i in range(17):
26     #     sum+= id_code_list[i] *int(id_code[i])
27     # verify=check_code_list[sum%11]
28     return id_code + str(verify_code)
29 print(day_age(25,'0820'))

这里涉及到了两个之前未接触过的东西:

1、zfill(width)函数:

width--原字符串右对齐,前面填充0
print('123'.zfill(5))
#00123

2、python中的推导式:

verify_code =check_code_list[sum(x*y for x,y in zip([x for x in id_code_list],[int(y) for y in id_code]))%11]
具体参考另一篇文章
 

猜你喜欢

转载自www.cnblogs.com/sgfg-1314/p/10109064.html
今日推荐