编写程序进行公民身份证信息验证,运行程序输入身份证号码,对所输入的身份证号码进行验证,验证身份证号码的校验位是否正确。如果正确,则输出该身份证的出生年月日。
时间: 2024-03-18 14:42:46 浏览: 222
好的,我可以为你提供一个Python程序来验证身份证号码的校验位是否正确,并输出出生年月日。以下是实现代码:
```python
import re
import datetime
# 验证身份证号码的函数
def validate_id_number(id_number):
# 身份证号码的正则表达式
pattern = re.compile(r'^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})(\d|[Xx])$')
match = pattern.match(id_number)
if not match:
return False
# 获取身份证号码中的各个字段
city_code = match.group(1)
year = match.group(2)
month = match.group(3)
day = match.group(4)
seq = match.group(5)
check_digit = match.group(6)
# 验证校验位
factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
check_sum = sum([int(id_number[i]) * factors[i] for i in range(17)])
remainder = check_sum % 11
check_digit_map = {0: '1', 1: '0', 2: 'X', 3: '9', 4: '8', 5: '7', 6: '6', 7: '5', 8: '4', 9: '3', 10: '2'}
if check_digit.upper() != check_digit_map[remainder]:
return False
# 返回出生年月日
birth_date_str = year + '-' + month + '-' + day
birth_date = datetime.datetime.strptime(birth_date_str, '%Y-%m-%d')
return birth_date
# 测试函数
id_number = input('请输入身份证号码:')
birth_date = validate_id_number(id_number)
if birth_date:
print('该身份证的出生年月日为:', birth_date.strftime('%Y年%m月%d日'))
else:
print('身份证号码不正确!')
```
在上述程序中,我们首先定义了一个正则表达式来匹配身份证号码,并获取了身份证号码中的各个字段。然后,我们使用Luhn算法来验证身份证号码的校验位是否正确。最后,如果身份证号码正确,我们就将出生年月日转换为Python的datetime对象,并输出到屏幕上。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)