Skip to content

Instantly share code, notes, and snippets.

@corpit
Last active August 8, 2019 22:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save corpit/8204456 to your computer and use it in GitHub Desktop.
Save corpit/8204456 to your computer and use it in GitHub Desktop.
UPC-A to UPC-E converter in Python
def upca_to_upce(upca):
"""
Takes a upc-a code (12 digits), including check digit,
as a string and returns upc-e representation.
UPC-E representation will be eight digits, including check digit
Returns None if no upc-e representation is possible
Rules from http://mdn.morovia.com/kb/UPCE-Specification-10634.html
Test for all numbers 0-9 (last digit of upce) in number system 0
Then test 1 number system 1 and one number system 2
>>> upca_to_upce("042100005264")
'04252614'
>>> upca_to_upce("020200004417")
'02044127'
>>> upca_to_upce("020600000019")
'02060139'
>>> upca_to_upce("040350000077")
'04035747'
>>> upca_to_upce("020201000050")
'02020150'
>>> upca_to_upce("020204000064")
'02020464'
>>> upca_to_upce("023456000073")
'02345673'
>>> upca_to_upce("020204000088")
'02020488'
>>> upca_to_upce("020201000098")
'02020198'
>>> upca_to_upce("043000000854")
'04308504'
>>> upca_to_upce("127200002013")
'12720123'
>>> upca_to_upce("212345678992")
"""
start_digit = upca[0]
check_digit = upca[11]
manufacturer_code = upca[1:6]
product_code = upca[6:11]
upce = None
if not start_digit in ['0', '1']:
return None
if manufacturer_code[-3:] in ["000", "100", "200"] and int(product_code) <= 999:
upce = manufacturer_code[:2] + product_code[-3:] + manufacturer_code[2]
elif manufacturer_code[-2:] == '00' and int(product_code) <= 99:
upce = manufacturer_code[:3] + product_code[-2:] + "3"
elif manufacturer_code[-1] == "0" and int(product_code) <= 9:
upce = manufacturer_code[:4] + product_code[-1] + "4"
elif manufacturer_code[-1] != "0" and int(product_code) in [5,6,7,8,9]:
upce = manufacturer_code + product_code[-1]
if upce is not None:
upce = start_digit + upce + check_digit
return upce
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment