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

本文实例讲述了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程序设计有所帮助。

(0)

相关推荐

  • python定时检查某个进程是否已经关闭的方法

    本文实例讲述了python定时检查某个进程是否已经关闭的方法.分享给大家供大家参考.具体如下: import threading import time import os import subprocess def get_process_count(imagename): p = os.popen('tasklist /FI "IMAGENAME eq %s"' % imagename) return p.read().count(imagename) def timer_star

  • PHP webshell检查工具 python实现代码

    1.使用方法:find.py 目录名称 2. 主要是采用python正则表达式来匹配的,可以在keywords中添加自己定义的正则,格式: ["eval\(\$\_POST","发现PHP一句话木马!"] #前面为正则,后面为对这个正则的描述,会在日志中显示. 3.修改下文件后缀和关键字的正则表达式就可以成为其他语言的webshell检查工具了,^_^. 4.开发环境是windows xp+ActivePython 2.6.2.2,家里电脑没有Linux环境,懒得装

  • 使用python检测主机存活端口及检查存活主机

    监测主机存活的端口 #!/usr/bin/env python # coding-utf import argparse import socket import sys #author: wolf_ribble def scan_ports(host,start_port,end_port): """Scan remote hosts""" try: sock = socket.socket(socket.AF_INET, socket.SOC

  • Python 检查数组元素是否存在类似PHP isset()方法

    PHP中有isset方法来检查数组元素是否存在,在Python中无对应函数. Python的编程理念是"包容错误"而不是"严格检查".举例如下: 复制代码 代码如下: Look before you leap (LBYL): if idx < len(array): array[idx] else: #handle this Easier to ask forgiveness than permission (EAFP): try: array[idx] ex

  • python定时检查启动某个exe程序适合检测exe是否挂了

    详见代码如下: 复制代码 代码如下: import threading import time import os import subprocess def get_process_count(imagename): p = os.popen('tasklist /FI "IMAGENAME eq %s"' % imagename) return p.read().count(imagename) def timer_start(): t = threading.Timer(120,

  • 21行Python代码实现拼写检查器

    引入 大家在使用谷歌或者百度搜索时,输入搜索内容时,谷歌总是能提供非常好的拼写检查,比如你输入 speling,谷歌会马上返回 spelling. 下面是用21行python代码实现的一个简易但是具备完整功能的拼写检查器. 代码 import re, collections def words(text): return re.findall('[a-z]+', text.lower()) def train(features): model = collections.defaultdict(

  • python代码检查工具pylint 让你的python更规范

    1.pylint是什么? Pylint 是一个 Python 代码分析工具,它分析 Python 代码中的错误,查找不符合代码风格标准(Pylint 默认使用的代码风格是 PEP 8,具体信息,请参阅参考资料)和有潜在问题的代码.目前 Pylint 的最新版本是 pylint-0.18.1. Pylint 是一个 Python 工具,除了平常代码分析工具的作用之外,它提供了更多的功能:如检查一行代码的长度,变量名是否符合命名标准,一个声明过的接口是否被真正实现等等. Pylint 的一个很大的好

  • Python实现单词拼写检查

    这几天在翻旧代码时发现以前写的注释部分有很多单词拼写错误,这些单词错得不算离谱,应该可以用工具自动纠错绝大部分.用 Python 写个拼写检查脚本很容易,如果能很好利用 aspell/ispell 这些现成的小工具就更简单了. 要点 1.输入一个拼写错误的单词,调用 aspell -a 后得到一些候选正确单词,然后用距离编辑进一步嗮选出更精确的词.比如运行 aspell -a,输入 'hella' 后得到如下结果: hell, Helli, hello, heal, Heall, he'll,

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

    本文实例讲述了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].l

  • python清除字符串里非字母字符的方法

    本文实例讲述了python清除字符串里非字母字符的方法.分享给大家供大家参考.具体如下: s = "hello world! how are you? 0" # Short version print filter(lambda c: c.isalpha(), s) # Faster version for long ASCII strings: id_tab = "".join(map(chr, xrange(256))) tostrip = "&quo

  • python转换字符串为摩尔斯电码的方法

    本文实例讲述了python转换字符串为摩尔斯电码的方法.分享给大家供大家参考.具体实现方法如下: chars = ",.0123456789?abcdefghijklmnopqrstuvwxyz" codes = """--..-- .-.-.- ----- .---- ..--- ...-- ....- ..... -.... --... ---.. ----. ..--.. .- -... -.-. -... . ..-. --. .... .. .-

  • Python删除字符串中字符的四种方法示例代码

    目录 一.删除字符串两端的一种或多种字符 二.删除字符串中单个固定位置的字符 三.删除字符串中任意位置的一种或多种字符 四.同时删除字符串内的多种不同字符 一.删除字符串两端的一种或多种字符 #strip().lstrip().rstrip()方法:(默认删除空格符) A.list.strip(字符):删除字符串两端的一种或多种字符: 例:删除字符串s两端 a 或 b 或 c 字符: s = 'abbmmmcccbbb' s1 = s.strip('abc') print(s1) #输出:mmm

  • Python判断字符串是否为空和null方法实例

    判断python中的一个字符串是否为空,可以使用如下方法 1.使用字符串长度判断 len(s) ==0 则字符串为空 #!/user/local/python/bin/python # coding=utf-8 test1 = '' if len(test1) == 0: print '字符串TEST1为空串' else: print '字符串TEST1不是空串,TEST1:' + test1 2.isspace判断是否字符串全部是空格 Python isspace() 方法检测字符串是否只由空

  • Python去除字符串前后空格的几种方法

    其实如果要去除字符串前后的空格很简单,那就是用strip(),简单方便 >>> ' A BC '.strip() 'A BC' 如果不允许用strip()的方法,也是可以用正则匹配的方法来处理. >>> s1 = ' A BC' >>> s2 = 'A BC ' >>> s3 = ' A BC ' >>> s4 = 'A BC' >>> def trim(s): ... import re ...

  • Python 中字符串拼接的多种方法

    python拼接字符串一般有以下几种方法: ①直接通过(+)操作符拼接 s = 'Hello'+' '+'World'+'!' print(s) 输出结果: Hello World! 使用这种方式进行字符串连接的操作效率低下,因为python中使用 + 拼接两个字符串时会生成一个新的字符串,生成新的字符串就需要重新申请内存,当拼接字符串较多时自然会影响效率. ②通过str.join()方法拼接 strlist=['Hello',' ','World','!'] print(''.join(str

  • python 检查是否为中文字符串的方法

    [目标需求] 查看某一个字符串是否为中文字符串 [解决办法] def check_contain_chinese(check_str): for ch in check_str: if u'\u4e00' <= ch <= u'\u9fff': return True else: return False [举例检验] check_contain_chinese('abcc') False check_contain_chinese('123') False check_contain_chi

  • Python中字符串的修改及传参详解

    发现问题 最近在面试的时候遇到一个题目,选择用JavaScript或者Python实现字符串反转,我选择了Python,然后写出了代码(错误的): #!/usr/bin/env python #-*-coding:utf-8-*- __author__ = 'ZhangHe' def reverse(s): l = 0 r = len(s) - 1 while l < r: s[l],s[r] = s[r],s[l] l += 1 r -= 1 return s 然后面试官问了两个问题: (1)

  • php使用mb_check_encoding检查字符串在指定的编码里是否有效

    mb_check_encoding - 检查字符串在指定的编码里是否有效PHP 版本要求: (PHP 4 >= 4.4.3, PHP 5 >= 5.1.3)说明:bool mb_check_encoding ([ string $var = NULL [, string $encoding = mb_internal_encoding() ]] )检查指定的字节流在指定的编码里是否有效.它能有效避免所谓的"无效编码攻击(Invalid Encoding Attack)".参

随机推荐