python校验身份证号码
时间: 2023-11-12 10:58:37 浏览: 42
可以使用第三方库 `id-validator` 来校验身份证号码。首先需要安装该库,可以使用以下命令进行安装:
```
pip install id-validator
```
然后可以使用以下代码进行身份证号码的校验:
```python
from id_validator import validator
id_number = '110101199003074518'
is_valid = validator.is_valid(id_number)
print(is_valid)
```
输出结果为 `True` 表示身份证号码校验通过,输出结果为 `False` 表示身份证号码校验不通过。
相关问题
python 校验身份证号
以下是一个python函数,可以用于校验身份证号是否合法:
```python
def validate_id_card(id_card):
"""
校验身份证号是否合法
"""
# 加权因子表
weight_factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
# 校验码表
check_codes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
# 身份证号码长度
id_card_length = len(id_card)
if id_card_length == 18:
# 18位身份证号码校验
# 计算校验位
total = 0
for i in range(17):
total += int(id_card[i]) * weight_factors[i]
check_code = check_codes[total % 11]
# 比较校验位
if id_card[-1] == check_code:
return True
else:
return False
elif id_card_length == 15:
# 15位身份证号码校验
return True
else:
# 身份证号码长度不正确
return False
```
使用方法:
```python
id_card = '身份证号码'
if validate_id_card(id_card):
print('身份证号码合法')
else:
print('身份证号码不合法')
```
python身份证号码校验
可以使用 Python 的正则表达式模块 `re` 来进行身份证号码的校验。
身份证号码的规则是:
1. 18 位身份证号码的最后一位是校验位,其他 17 位由数字和字母组成。
2. 校验位的计算规则是:将身份证号码前 17 位数字依次乘以对应的系数,再将结果相加,得到一个和值,然后用 11 取模,得到一个余数,最后根据余数查表得到对应的校验码进行比对。
下面是一个示例代码实现身份证号码的校验:
```python
import re
def validate_id_card(id_card):
# 18 位身份证号码的校验规则
pattern = r'^[1-9]\d{5}\d{4}\d{2}\d{2}(\d{2})([0-9]|X)$'
match = re.match(pattern, id_card)
if not match:
return False
# 计算校验位
factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
check_codes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
check_sum = sum([int(id_card[i])*factors[i] for i in range(17)])
check_code = check_codes[check_sum % 11]
# 比对校验位
return id_card[-1] == check_code
```
使用示例:
```python
id_card = '110101199003077457'
if validate_id_card(id_card):
print(f'{id_card} 是有效的身份证号码')
else:
print(f'{id_card} 不是有效的身份证号码')
```
输出结果:
```
110101199003077457 是有效的身份证号码
```