[Python] python检查字符串是否是正确的ISBN →→→→→进入此内容的聊天室

来自 , 2021-04-04, 写在 Python, 查看 134 次.
URL http://www.code666.cn/view/67b4e636
  1. def isISBN(isbn):  
  2.     """Checks if the passed string is a valid ISBN number."""  
  3.     if len(isbn) != 10 or not isbn[:9].isdigit():  
  4.         return False  
  5.     if not (isbn[9].isdigit() or isbn[9].lower() == "x"):  
  6.         return False  
  7.  
  8.     tot = sum((10 - i) * int(c) for i, c in enumerate(isbn[:-1]))  
  9.  
  10.     checksum = (11 - tot % 11) % 11  
  11.     if isbn[9] == 'X' or isbn[9] == 'x':  
  12.         return checksum == 10  
  13.     else:  
  14.         return checksum == int(isbn[9])  
  15.  
  16. ok = """031234161X 0525949488 076360013X 0671027360 0803612079
  17.        0307263118 0684856093 0767916565 0071392319 1400032806 0765305240"""  
  18. for code in ok.split():  
  19.     assert isISBN(code)  
  20.  
  21. bad = """0312341613 052594948X 0763600138 0671027364 080361207X 0307263110
  22.         0684856092 0767916567 0071392318 1400032801 0765305241 031234161
  23.         076530Y241 068485609Y"""  
  24. for code in bad.split():  
  25.     assert not isISBN(code)  
  26.  
  27. print "Tests of isISBN()passed."  
  28.  
  29. #//python/4582

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

这儿你可以回复上面这条便签

captcha