Elysia Tools
Mobile Navigation
Validierung
UPC/EAN-Arithmetik mit synthetischen Codes
Drei ausführbare Python-Beispiele prüfen Prüfziffern, Ablehnung und führende Nullen ohne Produktzuordnung.
Beispiele
Einträge in dieser Sammlung
Prüfziffern erzeugen
Starten Sie den Generator mit synthetischen Körpern von 7, 11 und 12 Ziffern.
# Synthetic arithmetic fixtures only; no GS1 assignment or product claim.
def check_digit(body: str) -> str:
if len(body) not in (7, 11, 12) or not body.isascii() or not body.isdigit():
raise ValueError("Expected 7, 11 or 12 ASCII digits")
total = sum(int(c) * (3 if i % 2 == 0 else 1)
for i, c in enumerate(reversed(body)))
return str((-total) % 10)
def valid(code: str) -> bool:
return (len(code) in (8, 12, 13) and code.isascii() and code.isdigit()
and check_digit(code[:-1]) == code[-1])
bodies = ["0000001", "00000000001", "000000000001"]
codes = [body + check_digit(body) for body in bodies]
assert codes == ["00000017", "000000000017", "0000000000017"]
assert all(valid(code) for code in codes)
print([len(code) for code in codes]) # [8, 12, 13]
Veränderte Kontrollen
Prüfen Sie Original, geänderte Prüfziffer, zu kurze Zeichenkette und Buchstaben.
# Synthetic arithmetic fixtures only; no GS1 assignment or product claim.
def check_digit(body: str) -> str:
if len(body) not in (7, 11, 12) or not body.isascii() or not body.isdigit():
raise ValueError("Expected 7, 11 or 12 ASCII digits")
total = sum(int(c) * (3 if i % 2 == 0 else 1)
for i, c in enumerate(reversed(body)))
return str((-total) % 10)
def valid(code: str) -> bool:
return (len(code) in (8, 12, 13) and code.isascii() and code.isdigit()
and check_digit(code[:-1]) == code[-1])
good = "000000000017"
bad = good[:-1] + "8"
assert valid(good)
assert not valid(bad)
assert not valid("00000000001") # wrong complete-code length
assert not valid("00000000001A") # not ASCII digits
print("one valid code; three invalid controls")
Führende Nullen erhalten
Entfernen Sie nur normale Leerzeichen und vergleichen Sie String und Ganzzahl.
# Synthetic arithmetic fixtures only; no GS1 assignment or product claim.
def check_digit(body: str) -> str:
if len(body) not in (7, 11, 12) or not body.isascii() or not body.isdigit():
raise ValueError("Expected 7, 11 or 12 ASCII digits")
total = sum(int(c) * (3 if i % 2 == 0 else 1)
for i, c in enumerate(reversed(body)))
return str((-total) % 10)
def valid(code: str) -> bool:
return (len(code) in (8, 12, 13) and code.isascii() and code.isdigit()
and check_digit(code[:-1]) == code[-1])
display = "0000 0000 0017"
code = display.replace(" ", "") # explicitly allow ordinary spaces only
assert code == "000000000017" and valid(code)
assert len(code) == 12
assert str(int(code)) == "17"
assert not valid(str(int(code)))
print("keep identifiers as strings: 12 characters, not 2")
Werkzeuge
Tools, die oft mit diesem Beispiel genutzt werden
Verwandt
Verwandte Beispielsammlungen
Verwandt