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.
Code
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"))
Report a problem with this exampleOpens a pre-filled issue on GitHub.