ISBN-13 由五组数字组成,最后一位是校验位。这是一个确保有五个组,正好是 13 位的函数,并验证校验位。它适用于您的样品:
import re
def validate(s):
d = re.findall(r'\d',s)
if len(d) != 13:
return False
if not re.match(r'97[89](?:-\d+){3}-\d$',s):
return False
# The ISBN-13 check digit, which is the last digit of the ISBN, must range from 0 to 9
# and must be such that the sum of all the thirteen digits, each multiplied by its
# (integer) weight, alternating between 1 and 3, is a multiple of 10.
odd = [int(x) for x in d[::2]]
even = [int(x)*3 for x in d[1::2]]
return (sum(odd)+sum(even)) % 10 == 0
trials = '''\
978-3-16-148410-0
978-3-16-148410
978-0-306-40615-7
978-0306-40615-7
979-11111-11-11-2
978-7654-321-12-4
977-7654-321-12-4
978-7654-321-1-41
978-7654-321-1-4
978-7654-321-122-4
'''.splitlines()
for trial in trials:
print(validate(trial),trial)
输出:
True 978-3-16-148410-0
False 978-3-16-148410 # too few numbers and groups
True 978-0-306-40615-7
False 978-0306-40615-7 # too few groups
True 979-11111-11-11-2
False 978-7654-321-12-4 # wrong check digit
False 977-7654-321-12-4 # didn't start with 978 or 979
False 978-7654-321-1-41 # didn't end in one digit.
False 978-7654-321-1-4 # too few digits
False 978-7654-321-122-4 # too many digits