UPC / EAN
[Date Prev][
Date Next]
[Thread Prev][
Thread Next]
UPC / EAN
- From: Jochen Garcke <jochen [at] garcke.de>
- To: python-stdnum-users [at] lists.arthurdejong.org
- Subject: UPC / EAN
- Date: Sun, 19 Jun 2011 12:05:30 +0200
Maybe of interest, feel free to use the code.
I needed to validate barcodes of the form UPC or EAN-13, with potential
additional EAN-2 or EAN-5 for periodicals, this code validates it.
Not sure if for a general code one would/should do the checks to remove
EAN5 and EAN2 though, one might get into trouble doing this always.
A separation into is_valid and calc_check_digit is obvious.
Jochen
def valid_barcode(barcode):
'''
validates a barcode
- ignore the check digit
- count from right to left
- add odd numbered times 3
- add even numbered
- 10 - (result modulo 10) is check digit
- check digit of 10 becomes 0
'''
# remove space and hyphens
barcode = str(barcode).replace('-', '').replace(' ', '')
try:
int(barcode)
except ValueError:
return False
# if extra 5 digits remove them (EAN 5)
if len(barcode) > 16:
barcode = barcode[:-5]
elif len(barcode) > 13:
# if extra 2 digits remove them (EAN 2)
barcode = barcode[:-2]
if len(barcode) > 13:
return False
odd = True
check_sum = 0
# odd/even from back
for number in barcode[:-1][::-1]:
if odd:
check_sum += int(number)*3
else:
check_sum += int(number)
odd = not odd
check_digit = 10 - (check_sum % 10)
if check_digit == 10:
check_digit = 0
if int(barcode[-1]) == check_digit:
return True
else:
return False
--
To unsubscribe send an email to
python-stdnum-users-unsubscribe@lists.arthurdejong.org or see
http://lists.arthurdejong.org/python-stdnum-users