How do I check if a value is a valid ISBN-13 number in Python?
Ava W
ava w profile pic

To check if a value is a valid ISBN-13 number in Python, you can follow these steps: 1. Remove non-digit characters: - Start by removing any non-digit characters from the value using there.sub() function. - This step ensures that only the digits remain for the subsequent validation. - Example:

1
2
3
4
5

import re

def clean_isbn(value):
    return re.sub(r"\D", "", value)

2. Validate the length: - Check if the cleaned value has a length of 13 digits. - If the length is not 13, the value cannot be a valid ISBN-13 number. - Example:

1
2
3

def has_valid_length(value):
    return len(value) == 13

3. Calculate the check digit: - Multiply each digit of the first 12 digits alternately by 1 and 3. - Sum up the results of these multiplications. - Subtract the sum from the nearest multiple of 10, and the result will be the check digit. - Example:

1
2
3
4
5

def calculate_check_digit(value):
    digits = list(map(int, value))
    check_digit = (10 - sum(digits[:12:2]) - sum(digits[1:12:2] * 3)) % 10
    return str(check_digit)

4. Validate the check digit: - Extract the last digit of the cleaned value as the actual check digit. - Calculate the check digit using the first 12 digits. - If the calculated check digit matches the actual check digit, the value is a valid ISBN-13 number. - Example:

1
2
3
4
5

def has_valid_check_digit(value):
    actual_check_digit = value[-1]
    calculated_check_digit = calculate_check_digit(value[:-1])
    return actual_check_digit == calculated_check_digit

5. Validate the ISBN-13: - Combine the previous validation steps to check if the value is a valid ISBN-13 number. - Example:

1
2
3
4

def is_valid_isbn_13(value):
    cleaned_value = clean_isbn(value)
    return has_valid_length(cleaned_value) and has_valid_check_digit(cleaned_value)

6. Use the function: - Call theis_valid_isbn_13() function and pass the value you want to check as an argument. - It will returnTrue if the value is a valid ISBN-13 number, andFalse otherwise. - Example:

1
2
3
4
5
6

isbn = "978-3-16-148410-0"
if is_valid_isbn_13(isbn):
    print("Valid ISBN-13")
else:
    print("Invalid ISBN-13")

By following these steps, you can efficiently check if a value is a valid ISBN-13 number in Python. This approach involves cleaning the value, validating its length, calculating and validating the check digit, and combining these validations to determine the validity of the ISBN-13 number.