2401_84411159 2024-04-25 07:42 采纳率: 0%
浏览 11

验证身份证信息,并输出出生日期

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

img

  • 写回答

6条回答 默认 最新

  • 专家-赤兔[在线] 优质创作者: 编程框架技术领域 2024-04-25 07:42
    关注

    引自免费微信小程序:皆我百晓生

    为了验证身份证信息并输出出生日期,我们可以编写一个Python函数,这个函数会检查输入的字符串是否符合18位身份证号码的格式,包括校验码的计算。以下是详细的步骤和对应的Python代码实现:

    1. 检查输入的字符串长度是否为18。
    2. 确保第17位是奇数代表男性,偶数代表女性。
    3. 计算校验码,校验码的计算规则如下:
      • 将前17位数字分别乘以不同的权重,权重从第一位到第十七位依次为7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2。
      • 把得到的结果相加。
      • 对结果取模11,余数为0时,校验码为10,即X;否则,校验码就是余数。
    4. 比较计算出的校验码与输入的第18位字符是否匹配。

    下面是完整的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的函数,它接受一个身份证号码作为参数,并根据上述步骤进行验证。如果验证通过,它将返回出生日期;如果不通过,则返回错误消息。在测试部分,我们提供了两个例子,一个是有效的身份证号码,另一个是无效的。

    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 4月25日