python检查字符串是否是正确的ISBN

2022-03-11 00:00:00 字符串 检查 正确

python检查字符串是否是正确的ISBN,ISBN书号是有一定的编码规则的,通过这个函数可以检查ISBN是否合法

"""
作者:皮蛋编程(https://www.pidancode.com)
创建日期:2022/3/21
功能描述:python检查字符串是否是正确的ISBN
"""


def isISBN(isbn):
    if len(isbn) != 10 or not isbn[:9].isdigit():
        return False
    if not (isbn[9].isdigit() or isbn[9].lower() == "x"):
        return False
    tot = sum((10 - i) * int(c) for i, c in enumerate(isbn[:-1]))
    checksum = (11 - tot % 11) % 11
    if isbn[9] == 'X' or isbn[9] == 'x':
        return checksum == 10
    else:
        return checksum == int(isbn[9])


print(isISBN('031234161X'))
print(isISBN('0312341613'))

输出结果:
True
False

以上代码在Python3.9环境下测试通过

相关文章