python验证身份证

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

声明:具体参考谁的博客忘了,如有雷同请私聊,加链接。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值