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

yipeiwu_com5年前Python基础

本文实例讲述了python检查字符串是否是正确ISBN的方法。分享给大家供大家参考。具体实现方法如下:

def isISBN(isbn): 
  """Checks if the passed string is a valid ISBN number.""" 
  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]) 
ok = """031234161X 0525949488 076360013X 0671027360 0803612079 
    0307263118 0684856093 0767916565 0071392319 1400032806 0765305240""" 
for code in ok.split(): 
  assert isISBN(code) 
bad = """0312341613 052594948X 0763600138 0671027364 080361207X 0307263110 
     0684856092 0767916567 0071392318 1400032801 0765305241 031234161 
     076530Y241 068485609Y""" 
for code in bad.split(): 
  assert not isISBN(code) 
print "Tests of isISBN()passed." 

希望本文所述对大家的Python程序设计有所帮助。

相关文章

学习python中matplotlib绘图设置坐标轴刻度、文本

学习python中matplotlib绘图设置坐标轴刻度、文本

总结matplotlib绘图如何设置坐标轴刻度大小和刻度。 上代码: from pylab import * from matplotlib.ticker import Multi...

对Pandas DataFrame缺失值的查找与填充示例讲解

查看DataFrame中每一列是否存在空值: temp = data.isnull().any() #列中是否存在空值 print(type(temp)) print(temp)...

判断网页编码的方法python版

在web开发的时候我们经常会遇到网页抓取和分析,各种语言都可以完成这个功能。我喜欢用python实现,因为python提供了很多成熟的模块,可以很方便的实现网页抓取。 但是在抓取过程中会...

初步解析Python下的多进程编程

要让Python程序实现多进程(multiprocessing),我们先了解操作系统的相关知识。 Unix/Linux操作系统提供了一个fork()系统调用,它非常特殊。普通的函数调用,...

Python numpy数组转置与轴变换

Python numpy数组转置与轴变换

这篇文章主要介绍了Python numpy数组转置与轴变换,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 矩阵的转置 >&...