Last active
August 29, 2015 13:56
-
-
Save gabalese/9326336 to your computer and use it in GitHub Desktop.
Script to check the formal validity of a given ISBN-10 or ISBN-13.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python | |
import sys | |
import re | |
def is_valid(isbn): | |
sum = 0 | |
isbn = re.sub(r"[-–—\s]", "", isbn) | |
# in case of isbn13 | |
if len(isbn) == 13 and isbn[0:3] == "978" or "979": # is it a ISBN? Thanks @librarythingtim | |
for d, i in enumerate(isbn): | |
if (int(d) + 1) % 2 != 0: | |
sum += int(i) | |
else: | |
sum += int(i) * 3 | |
if sum % 10 == 0: | |
return True | |
else: | |
return False | |
# in case of isbn10 | |
elif len(isbn) == 10: | |
isbn = list(isbn) | |
if isbn[-1] == "X" or isbn[-1] == "x": # a final x stands for 10 | |
isbn[-1] = 10 | |
for d, i in enumerate(isbn[:-1]): | |
sum += (int(d)+1) * int(i) | |
if (sum % 11) == int(isbn[-1]): | |
return True | |
else: | |
return False | |
else: | |
return False | |
if __name__ == "__main__": | |
if is_valid(sys.argv[1]): | |
print sys.argv[1], "\t", "is a valid ISBN" | |
else: | |
print sys.argv[1], "\t", "is NOT a valid ISBN" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment