python实现验证输入的18为身份证号码是否合法
时间: 2024-06-10 18:04:29 浏览: 215
可以使用以下代码实现:
```python
import re
def validate_id_card(id_card):
if len(id_card) != 18:
return False
if not re.match(r'^\d{17}(\d|x|X)$', id_card):
return False
# 验证省份
provinces = ['11','12','13','14','15','21','22','23','31','32','33','34','35','36','37','41','42','43','44','45','46','50','51','52','53','54','61','62','63','64','65','71','81','82']
if id_card[:2] not in provinces:
return False
# 验证生日
year = int(id_card[6:10])
month = int(id_card[10:12])
day = int(id_card[12:14])
try:
birthday = datetime.datetime(year, month, day)
if birthday != datetime.datetime.strptime(id_card[6:14],'%Y%m%d'):
return False
except ValueError:
return False
# 验证校验码
factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
check_sum = sum([int(id_card[i])*factors[i] for i in range(17)]) % 11
check_codes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
if id_card[-1].lower() != check_codes[check_sum]:
return False
return True
```
该函数会对输入的身份证号码进行长度、格式、省份、出生日期和校验码的验证,如果身份证合法,则返回`True`,否则返回`False`。
阅读全文