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

yipeiwu_com6年前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在安装的时候,就自带了很多模块,我们把这些模块称之为标准库,其中,有一个是使用频率比较高的,就是 os 。这个库中方法和属性众多,有兴趣的看官可以参考官方文档:https:/...

python进程间通信Queue工作过程详解

Process之间有时需要通信,操作系统提供了很多机制来实现进程间的通信。 1. Queue的使用 可以使用multiprocessing模块的Queue实现多进程之间的数据传递,Que...

对django 模型 unique together的示例讲解

unique_together 这个元数据是非常重要的一个!它等同于数据库的联合约束! 举个例子,假设有一张用户表,保存有用户的姓名、出生日期、性别和籍贯等等信息。要求是所有的用户唯一不...

使用Python判断IP地址合法性的方法实例

使用Python判断IP地址合法性的方法实例

一、使用方法和执行效果请看图:二、python实现代码:复制代码 代码如下:[root@yang python]# vi check_ip.py #!/usr/bin/python im...

在Python中处理字符串之isdigit()方法的使用

 isdigit()方法检查字符串是否只包含数字(全由数字组成)。 语法 以下是isdigit()方法的语法: str.isdigit() 参数  &...