Validate ISBN-10 and ISBN-13 Checksums

Normalize hyphens and spaces, then verify ISBN-10 and ISBN-13 check digits with the official weighted modulo rules.

PythonForm Validation

Code

pythonsnippet
37 lines
import re


def normalize(value: str) -> str:
    cleaned = re.sub(r"[\s-]", "", value).upper()
    if not re.fullmatch(r"\d{9}[\dX]|\d{13}", cleaned):
        raise ValueError("not an ISBN-10 or ISBN-13")
    return cleaned


def isbn10_valid(value: str) -> bool:
    total = 0
    for index, char in enumerate(value):
        digit = 10 if char == "X" else int(char)
        total += (10 - index) * digit
    return total % 11 == 0


def isbn13_valid(value: str) -> bool:
    total = sum(
        (1 if index % 2 == 0 else 3) * int(char)
        for index, char in enumerate(value)
    )
    return total % 10 == 0


def validate(value: str) -> dict[str, object]:
    code = normalize(value)
    valid = isbn10_valid(code) if len(code) == 10 else isbn13_valid(code)
    return {"isbn": code, "format": len(code), "valid": valid}


if __name__ == "__main__":
    print(validate("0-306-40615-2"))
    print(validate("978-0-306-40615-7"))
    print(validate("978-0-306-40615-8"))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

{'isbn': '0306406152', 'format': 10, 'valid': True}
{'isbn': '9780306406157', 'format': 13, 'valid': True}
{'isbn': '9780306406158', 'format': 13, 'valid': False}

How the snippet works

Count the functions normalize, isbn10_valid, isbn13_valid and validate as the entire surface area of Validate ISBN-10 and ISBN-13 Checksums.

Repetition is confined to for index, char in enumerate(value) — the rest of the file is straight-line. Instead of silently continuing, the code raises ValueError at the guard.

The result is a fresh construction, so callers can keep their originals.

Caveats

  • The guard not re.fullmatch(r"\d{9}[\dX]|\d{13}", cleaned) short-circuits the flow with an early raise when its condition holds.

Using it

The primary signature is def normalize(value: str) -> str

Key statements

return {"isbn": code, "format": len(code), "valid": valid}
def isbn10_valid(value: str) -> bool:
    total = 0
    for index, char in enumerate(value):
        digit = 10 if char == "X" else int(char)
        total += (10 - index) * digit
    return total % 11 == 0
def isbn13_valid(value: str) -> bool:
    total = sum(
        (1 if index % 2 == 0 else 3) * int(char)
        for index, char in enumerate(value)
    )
    return total % 10 == 0

Interactive Tools for This Topic

FAQ

Does `normalize` modify its input?
It does not. Inputs are only read; the return value is freshly built.
What does the snippet do with malformed data?
The code refuses to continue: `ValueError` is thrown while the state is still recoverable.
How do you run Validate ISBN-10 and ISBN-13 Checksums?
It runs as-is — treat the file as the whole program and execute it.