Python身份证号码验证
时间: 2023-11-05 18:03:55 浏览: 147
Python身份证号验证
以下是Python代码,用于验证中国大陆身份证号码的有效性:
```python
import re
def validate_id_number(id_number):
# 正则表达式验证身份证格式
pattern = re.compile(r'^\d{17}[\dXx]$')
if not pattern.match(id_number):
return False
# 加权因子
weight_factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
# 校验码
check_code = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
id_list = list(id_number)
# 计算前17位数字的加权和
sum = 0
for i in range(17):
sum += int(id_list[i]) * weight_factor[i]
# 计算校验码
check_index = sum % 11
if id_list[17].upper() != check_code[check_index]:
return False
return True
```
使用示例:
```python
id_number = '110101199003074518'
if validate_id_number(id_number):
print('身份证号码有效')
else:
print('身份证号码无效')
```
输出:
```
身份证号码有效
```
阅读全文