类型:字符串
题目:验证身份证信息,并输出出生日期
python123

关注引自免费微信小程序:皆我百晓生
为了验证身份证信息并输出出生日期,我们可以编写一个Python函数,这个函数会检查输入的字符串是否符合18位身份证号码的格式,包括校验码的计算。以下是详细的步骤和对应的Python代码实现:
下面是完整的Python代码实现:
def validate_and_output_birthday(identification_number):
# Step 1: Check length
if len(identification_number) != 18:
return "身份证校验错误"
# Step 2: Check gender
gender = identification_number[16]
if not (gender.isdigit() and int(gender) % 2 == 0):
return "身份证校验错误"
# Step 3: Calculate the check digit
weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
sum_of_products = sum(int(digit) * weight for digit, weight in zip(identification_number[:17], weights))
check_digit_calculated = (sum_of_products % 11) % 10
# If the calculated check digit is 10, the actual digit should be X
check_digit_calculated = 'X' if check_digit_calculated == 10 else str(check_digit_calculated)
# Step 4: Compare the calculated check digit with the given one
if check_digit_calculated != identification_number[-1].upper():
return "身份证校验错误"
# Output the birthdate
birthdate = f"出生于{identification_number[6:10]}年{identification_number[10:12]}月{identification_number[12:14]}日"
return birthdate
# Test cases
print(validate_and_output_birthday("432831196411150810")) # 出生于1964年11月15日
print(validate_and_output_birthday("432831196811150810")) # 身份证校验错误
这段代码定义了一个名为validate_and_output_birthday的函数,它接受一个身份证号码作为参数,并根据上述步骤进行验证。如果验证通过,它将返回出生日期;如果不通过,则返回错误消息。在测试部分,我们提供了两个例子,一个是有效的身份证号码,另一个是无效的。