ISBN-13 requires 13 digits to be valid. Your code does not check that all characters are digits (excluding the -
separator), nor does it check the actual length. Also, five parts are required, and you could be verifying the check digit.
Specifically your code fails to ever return True
because the fourth segment (lst[3]
) checks for exactly one character (if len(lst[3])==1:
), however, that element will typically be longer than 1 digit.
There are python libraries available via PyPI that can validate ISBN codes. Here's an example using isbnlib
:
>>> import isbnlib
>>> isbnlib.is_isbn13('978-3-16-148410-0')
True
>>> isbnlib.is_isbn13('978-3-16-148410-5')
False
>>> isbnlib.is_isbn13('978-3-16-148410-A')
False
>>> isbnlib.is_isbn13('979-3-16-148410-9')
True
Another, lighter weight library is pyisbn
:
>>> import pysisbn
>>> pyisbn.validate('979-3-16-148410-9')
True
>>> pyisbn.validate('979-3-16-148410-0')
False
The advantage of using these libraries, other than saving you the hassle of parsing ISBN strings yourself, is that they offer additional functionality such as converting from ISBN-13 to ISBN-10.