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 多进程和数据传递的理解

Python 多进程和数据传递的理解 python不仅线程用的是系统原生线程,进程也是用的原生进程 进程的用法和线程大同小异 import multiprocessing...

Python re模块介绍

Python中转义字符 正则表达式使用反斜杠” \ “来代表特殊形式或用作转义字符,这里跟Python的语法冲突,因此,Python用” \\\\ “表示正则表达式中的” \ “,因为正...

pycharm中使用anaconda部署python环境的方法步骤

pycharm中使用anaconda部署python环境的方法步骤

今天来说一下python中一个管理包很好用的工具anaconda,可以轻松实现python中各种包的管理。相信大家都会有这种体验,在pycharm也是有包自动搜索和下载的功能,这个我在前...

Python二进制串转换为通用字符串的方法

一个小问题 今天在做一个实验时,需要对一个包含中英文词汇的TXT文件进行读入和整理。 Python代码的编码规则为UTF-8。在读入时,文件的每行是二进制串,形如: b'heroes...

Python入门之三角函数全解【收藏】

Python中的三角函数位于math模块内。 引入模块: import math 输出pi: import math print(math.pi) 得:3.14159265358979...