import re
#用正则校验身份证号码是否合法,合法就print true
def check_idcard(idcard):
if not isinstance(idcard, str):
return False
# 15位和18位身份证号码的正则表达式
regex = re.compile(r'^\d{15}$|^\d{18}$|^\d{17}(\d|X|x)$')
# 如果通过该验证,说明身份证格式正确,但准确性还需计算
if re.match(regex, idcard):
if len(idcard) == 18:
# 18位身份证需要验证最后一位校验位
# 将前17位加权因子保存在列表里
idcard_list = list(idcard)
idcard_list.pop()
idcard_list = list(map(int, idcard_list))
idcard_list = [a * b for a, b in zip(idcard_list, [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2])]
# 计算模(固定算法)
mode = sum(idcard_list) % 11
# 将计算出的模与11取余得到对应的校验位
check_code = {0: '1', 1: '0', 2: 'X', 3: '9', 4: '8', 5: '7', 6: '6', 7: '5', 8: '4', 9: '3', 10: '2'}
# 获取最后一位身份证号码
last_code = idcard[-1]
# 如果与算出来的校验位不一致,那么就是无效的身份证号码
if check_code[mode] != last_code.upper():
return False
else:
return True
else:
return True
else:
return False
idcard='000000000000000000'
print(check_idcard(idcard))
Last modification:March 23, 2023
© Reprint prohibited