Skip to content

Instantly share code, notes, and snippets.

@jrgcubano
Forked from jorgebastida/gist:1886036
Created September 5, 2016 16:12
Show Gist options
  • Save jrgcubano/d61244a29b0d1271e49c05826ea65cdf to your computer and use it in GitHub Desktop.
Save jrgcubano/d61244a29b0d1271e49c05826ea65cdf to your computer and use it in GitHub Desktop.
Get credit card type by number
import re
def credit_card_type(number):
"""
Return a string that represents the type of the credit card number.
Criteria:
AMEX: Starts with 34 or 37 and the length 15.
MASTERCARD: Starts with 51-55 and the length is 16.
VISA: Starts with 4 and the length is 13 or 16.
DINNERSCLUB: Starts with 300-306 and the length is 14.
ENROUTE: Starts with 2014 or 2149 and the length is 15.
DISCOVER: Starts with 6011 and the length is 16.
If the number don't match with any criteria return None.
Inspired in this script: http://javascript.gakaa.com/credit-card-type-by-number.aspx
"""
number = re.sub(r'\s', '', number)
def tsrange(*args):
"""Returns a tuple of string"""
return tuple(map(str, range(*args)))
known_cards = [['AMEX', ('34', '37'), [15]],
['MASTERCARD', tsrange(51, 56), [16]],
['VISA', ('4'), [13, 16]],
['DINNERSCLUB', tsrange(300, 306), [14]],
['ENROUTE', ('2014', '2149'), [15]],
['DISCOVER', ('6011'), [16]],
['JCB', ('3'), [16]],
['JCB', ('2131', '1800'), [15]]]
for card_type, starts, length in known_cards:
if number.startswith(starts) and len(number) in length:
return card_type
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment