How do I check if a value is a valid ISBN-10 or ISBN-13 number in Python using regex?
Ava W
ava w profile pic

To check if a value is a valid ISBN-10 or ISBN-13 number in Python using regex, you can follow these steps: 1. Import there module:

1
2
3

   import re
   

2. Define a function to check if the value is a valid ISBN-10 or ISBN-13 number:

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

   def is_valid_isbn(isbn):
  # Remove hyphens and whitespace from the ISBN string
  isbn = re.sub(r'[-\s]', '', isbn)

  # Check if the ISBN is either ISBN-10 or ISBN-13 format
  if re.match(r'^\d{9}[\d|X]$|^(\d{3}-){2}\d{3}-[\d|X]$', isbn):

 # Check if it is a valid ISBN-10 number
 if len(isbn) == 10:
check_digit = 0
for i, digit in enumerate(isbn[:-1]):
    check_digit += int(digit) * (10 - i)
check_digit = (11 - (check_digit % 11)) % 11
return str(check_digit) == isbn[-1] or (check_digit == 10 and isbn[-1] == 'X')

 # Check if it is a valid ISBN-13 number
 elif len(isbn) == 13:
check_digit = 0
for i, digit in enumerate(isbn[:-1]):
    weight = 1 if i % 2 == 0 else 3
    check_digit += int(digit) * weight
check_digit = (10 - (check_digit % 10)) % 10
return str(check_digit) == isbn[-1]

  return False
   

3. Call theis_valid_isbn function and pass the value to be checked:

1
2
3
4
5
6
7

   isbn = "978-0-306-40615-7"
   if is_valid_isbn(isbn):
  print("Valid ISBN number")
   else:
  print("Invalid ISBN number")
   

In theis_valid_isbn function, there.sub function is used to remove hyphens and whitespace from the ISBN string, ensuring that only the digits and 'X' (for ISBN-10 check digit) remain. The function then checks if the ISBN matches either the ISBN-10 or ISBN-13 format using regular expressions. The regex patternr'^\d{9}[\d|X]$|^(\d{3}-){2}\d{3}-[\d|X]$' is used to match the ISBN format, allowing for both hyphenated and non-hyphenated versions. If the ISBN matches either format, the function proceeds to check if it is a valid ISBN-10 or ISBN-13 number. For ISBN-10 numbers, the function calculates the check digit using a weighted sum of the first 9 digits. It compares the calculated check digit with the last digit of the ISBN to determine its validity. If the check digit is 10, it can be represented by 'X'. For ISBN-13 numbers, the function calculates the check digit using a weighted sum of the first 12 digits. It compares the calculated check digit with the last digit of the ISBN to determine its validity. If the ISBN passes the checks for the specific format and check digit, the function returnsTrue, indicating that the ISBN number is valid. Otherwise, it returnsFalse. You can modify the code to include any additional checks or modify the regex pattern to suit your specific requirements. Use theis_valid_isbn function to check if a value is a valid ISBN-10 or ISBN-13 number in your Python programs.