How can I check if a string is a valid ISBN-10 or ISBN-13 number in Python?
Ava W
ava w profile pic

To check if a string is a valid ISBN-10 or ISBN-13 number in Python, you can follow these steps: 1. Remove any non-digit characters from the string:

1
2
3

   isbn = ''.join(filter(str.isdigit, isbn))
   

2. Determine if the string represents an ISBN-10 or ISBN-13 based on its length:

1
2
3
4
5
6
7
8

   if len(isbn) == 10:
  # ISBN-10 validation
   elif len(isbn) == 13:
  # ISBN-13 validation
   else:
  # Invalid length, not a valid ISBN
   

3. Validate the checksum for ISBN-10: For an ISBN-10, the last character can be a digit or 'X', which represents 10. The checksum calculation is as follows:

1
2
3
4
5
6
7
8
9
10
11

   checksum = 0
   for i in range(9):
  checksum += (i + 1) * int(isbn[i])
   checksum %= 11

   if (checksum == int(isbn[9]) or (checksum == 10 and isbn[9] == 'X')):
  # Valid ISBN-10
   else:
  # Invalid ISBN-10
   

4. Validate the checksum for ISBN-13: For an ISBN-13, the last character is a digit calculated based on the previous 12 digits. The checksum calculation is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13

   checksum = 0
   for i in range(12):
  weight = 1 if i % 2 == 0 else 3
  checksum += weight * int(isbn[i])
   checksum %= 10
   checksum = 10 - checksum if checksum != 0 else 0

   if checksum == int(isbn[12]):
  # Valid ISBN-13
   else:
  # Invalid ISBN-13
   

Here's a complete function that encapsulates the above steps:

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
29
30
31
32

def is_valid_isbn(isbn):
    isbn = ''.join(filter(str.isdigit, isbn))
    if len(isbn) == 10:
   # ISBN-10 validation
   checksum = 0
   for i in range(9):
  checksum += (i + 1) * int(isbn[i])
   checksum %= 11

   if (checksum == int(isbn[9]) or (checksum == 10 and isbn[9] == 'X')):
  return True
   else:
  return False

    elif len(isbn) == 13:
   # ISBN-13 validation
   checksum = 0
   for i in range(12):
  weight = 1 if i % 2 == 0 else 3
  checksum += weight * int(isbn[i])
   checksum %= 10
   checksum = 10 - checksum if checksum != 0 else 0

   if checksum == int(isbn[12]):
  return True
   else:
  return False

    else:
   # Invalid length, not a valid ISBN
   return False

You can use this function to check if a given string is a valid ISBN-10 or ISBN-13 number by callingis_valid_isbn(isbn) and passing the string to be checked as theisbn argument. The function will returnTrue if the ISBN is valid andFalse otherwise.