# The Luhn Algorithm to check a bank card's check sum. # Plus a regular expression to narrow the options. import re def add_digits(string): '''Converts the chars of string into ints and adds them. string must only consist of digits ''' return sum([int(c) for c in string]) def luhn(string): '''Print a result determined by the string and Luhn algorithm. 'possible' if string is ok 'invalid' if string is not. ''' total = 0 odd = False for c in reversed(string): if odd: n = int(c) * 2 total += add_digits(str(n)) else: total += int(c) odd = not odd print('possible' if total % 10 == 0 else 'invalid') # The regex will accept any 16 digit number which has 4 groups of 4 digits. # Each of the groups is separated by a space or a dash '-'. # There can be text before or after the card number. card = 'my card number is 1234 5678 9012 3452 don\'t tell anyone.' pattern = r'\b(\d{4}[ -]){3}\d{4}\b' match = re.search(pattern, card) if match: print(match.group(), '- ', end='') number = match.group().replace(' ','') luhn(number)