Python判断字符串是否为身份证格式
时间: 2025-01-19 07:05:34 浏览: 41
在Python中,判断一个字符串是否符合中国大陆居民身份证号码(18位或15位数字加4位校验码)的格式,通常需要编写正则表达式来完成。下面是一个简单的示例:
```python
import re
def is_valid_id(id_str):
# 正则表达式匹配15位或18位身份证号格式,以及最后一位校验码的计算规则
regex = r"^(^\d{15}$|^\d{18}(\d|X|x)$)"
# 检查字符串是否匹配正则表达式
if re.match(regex, id_str):
# 对于最后一位校验码,可以尝试计算并验证
id_parts = id_str[:-1] # 提取前17位
check_digit = calculate_check_digit(id_parts) # 自定义校验码计算函数
return id_parts + str(check_digit) == id_str
else:
return False
# 自定义计算第18位校验码的函数(中国标准算法)
def calculate_check_digit(digits):
weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
total = sum(a * b for a, b in zip(digits, weights)) % 11
return '10X'[total > 1]
# 测试
id_to_test = "123456789012345678"
if is_valid_id(id_to_test):
print(f"{id_to_test} 是有效的身份证")
else:
print(f"{id_to_test} 不是有效的身份证")
阅读全文
相关推荐


















