ActiveState Code

Recipe 498104: ISBN-13 converter


ISBN, the International Standard Book Number, will migrate to 13-digits version from current 10-digits version on 2007-01-01. This recipe converts ISBN-10 to ISBN-13 by regenerating the check digit.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
def check_digit_10(isbn):
    assert len(isbn) == 9
    sum = 0
    for i in range(len(isbn)):
        c = int(isbn[i])
        w = i + 1
        sum += w * c
    r = sum % 11
    if r == 10: return 'X'
    else: return str(r)

def check_digit_13(isbn):
    assert len(isbn) == 12
    sum = 0
    for i in range(len(isbn)):
        c = int(isbn[i])
        if i % 2: w = 3
        else: w = 1
        sum += w * c
    r = 10 - (sum % 10)
    if r == 10: return '0'
    else: return str(r)

def convert_10_to_13(isbn):
    assert len(isbn) == 10
    prefix = '978' + isbn[:-1]
    check = check_digit_13(prefix)
    return prefix + check

Comments

  1. 1. At 10:41 a.m. on 1 sep 2007, greg p said:

    Web Based Implementation. I put this recipe into an online calculator:

    http://www.utilitymill.com/utility/ISBN_10_to_ISBN_13_Converter

    I hope it's useful.

  2. 2. At 10:26 p.m. on 31 jan 2008, Osvaldo Santana said:

    Small command line utility. Hi,

    I've created a small utility based on this module and I've make some changes on the code too. Take a look at:

    http://osantana-code.googlecode.com/svn/trunk/others/isbn.py

    Thanks, Osvaldo

  3. 3. At 12:29 p.m. on 23 jul 2009, Michael Schmidt said:

    Thanks a lot! Save me a lot of time ...

    Michael

Sign in to comment