python身份证校验
时间: 2023-11-04 07:59:59 浏览: 523
可以使用Python编写代码验证身份证号码的合法性。以下是Python代码示例:
```
import re
def is_valid_ID_number(id_number):
if not re.match(r'^\d{17}[\dX]$', id_number):
return False
# 验证省份代码
province_code = id_number[:2]
if province_code not in {'11', '12', ..., '82', '21', '22', ..., '65'}:
return False
# 验证出生日期
year = int(id_number[6:10])
month = int(id_number[10:12])
day = int(id_number[12:14])
try:
birth_date = datetime.date(year, month, day)
except ValueError:
return False
# 验证最后一位校验码
factors = list(range(2, 19))[::-1] # 从高位到低位依次乘以权数
check_digit = id_number[-1]
if check_digit == 'X':
check_digit = 10
else:
check_digit = int(check_digit)
weighted_sum = sum(int(digit) * factor for digit, factor in zip(id_number[:-1], factors))
remainder = weighted_sum % 11
expected_check_digit = (12 - remainder) % 11
if check_digit != expected_check_digit:
return False
return True
# 示例用法
id_number = '340523199001018491'
if is_valid_ID_number(id_number):
print(f'{id_number} 是一个合法的身份证号码')
else:
print(f'{id_number} 不是一个合法的身份证号码')
```
注意,本文仅提供了一个Python的示例代码,不对该程序的正确性和可靠性做任何保证。在实际应用中,请结合业务需求和实际情况进行测试与修改。
阅读全文