IBAN number check refreshed


Picked up from old thread but currently applicable (the IBAN number became more widely required actually this year in Finland). The style was quite alien for modern Python coders, so I massaged the code to my own liking. I removed many temporary variables, as for my opinion they did not make things cleared, and I reformed map lambdas to generators.

About the Author

IT Pro doing Eng-Fin-Eng translations

# Utility to check the integrity of an IBAN bank account No.
# based on old code in thread: http://www.daniweb.com/software-development/python/threads/238464
# Dictionaries - Refer to ISO 7064 mod 97-10 
letter_dic={"A":10, "B":11, "C":12, "D":13, "E":14, "F":15, "G":16, "H":17, "I":18, "J":19, "K":20, "L":21, "M":22,
            "N":23, "O":24, "P":25, "Q":26, "R":27, "S":28, "T":29, "U":30, "V":31, "W":32, "X":33, "Y":34, "Z":35,

# ISO 3166-1 alpha-2 country code
             "CZ":[24,"Czech Republic"],
             "FO":[18,"Faroe Islands"],
             "NO":[15,"Northern Ireland"],
             "SM":[27,"San Marino"],
             "SA":[24,"Saudi Arabia"],
             "GB":[22,"United Kingdom"]}

def check(orig):
    block = 4
    # remove spaces from formatted 
    IBAN = ''.join(c for c in orig if c.isalnum())
    IBAN = IBAN[4:] + IBAN[:4]
    country = IBAN[-4:-2]
    if country not in country_dic:
        raise ValueError('Unknown IBAN country %s' % country)

    length_c, name_c = country_dic[country]

    if len(IBAN) != length_c:
        diff = len(IBAN) - length_c
        raise ValueError('Wrong IBAN length by %s: %s' % (('short by %i' % -diff) if diff < 0 else
                                                          ('too long by %i' % diff), orig))
    elif int("".join(str(letter_dic[x]) for x in IBAN)) % 97 != 1:
        raise ValueError('Incorrect IBAN number: %s' % orig)
        # Accepted: 
        # move IBAN to original order
        IBAN = IBAN[-4:] + IBAN[:-4]
        # return formatted number with spaces
        return ' '.join(IBAN[f:f+block] for f in range(0, len(IBAN), block))

if __name__ == '__main__':
    # Sample IBAN account numbers.
    for  IBAN in ("GB35MIDL40253432144670", "BE31435411161155", "CH5108686001256515001", raw_input("Enter account No. : ").upper()):
            formatted = check(IBAN)
        except ValueError as e:
            print("IBAN account No. accepted.")
            print("Formated bank account No : %s\n" % formatted)
TrustyTony 888 pyMod Team Colleague Featured Poster

Of course there is more consise way of doing the first line, but it does not really matter:

letter_dic= dict((letter, ind) for ind, letter in enumerate("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.