def get_checkcode(id):
"""
计算身份证号码的校验位;
:param:
* id_number_str: (string) 身份证号的前17位,比如 3201241987010100
:returns:
* 返回类型 (tuple)
* flag: (bool) 如果身份证号格式正确,返回 True;格式错误,返回 False
* checkcode: 计算身份证前17位的校验码
举例如下::
from fishbase.fish_data import *
print('--- fish_data idcard_get_checkcode demo ---')
# id number
id1 = '32012419870101001'
print(id1, idcard_get_checkcode(id1)[1])
# id number
id2 = '13052219840731647'
print(id2, idcard_get_checkcode(id2)[1])
print('---')
输出结果::
--- fish_data idcard_get_checkcode demo ---
32012419870101001 5
13052219840731647 1
---
"""
id_number_str = id[:-1]
id_end_str = id[-1:]
# 判断长度,如果不是 17 位,直接返回失败
if len(id_number_str) != 17:
return False
id_regex = '[1-9][0-9]{14}([0-9]{2}[0-9X])?'
if not re.match(id_regex, id_number_str):
return False
items = [int(item) for item in id_number_str]
# 加权因子表
factors = (7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2)
# 计算17位数字各位数字与对应的加权因子的乘积
copulas = sum([a * b for a, b in zip(factors, items)])
# 校验码表
check_codes = ('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2')
checkcode = check_codes[copulas % 11].upper()
if checkcode != id_end_str:
return False
return True
声明:具体参考谁的博客忘了,如有雷同请私聊,加链接。