pythonisbn

python isbn 13 digit validate


I need to write a function that validates a 13 digit ISBN. It needs to start with 978 or 979, end with a single digit, and the remaining sections need to be at least 1 digit in length. I need some help to make this work, I don't understand why it never returns true

def validate(s)
 lst = s.split("-")
 isbn= False
 if lst[0] == "978" or lst[0] == "979":
     if len(lst[1])>=1 and len(lst[2])>=1:
         if len(lst[3])==1:
            isbn= True
return isbn

Solution

  • You should use regular expression and this is exactly why it is used for:

    >>> import re
    >>> def validate(isbn):
            isbn_regex = re.compile('^(978|979)-\d+-\d+-\d$')
            return isbn_regex.search(isbn) is not None
    
    >>> print validate('978-12-12-2')
        True
    

    Note: This works as per your logic in the above code(except for you didn't check whether it's a digit).