String Module Constants Build Code Alphabets

string.ascii_uppercase plus string.digits defines the 36 legal characters for redeem codes; normalization absorbs separators, spaces and casing.

PythonData Integrity

Code

pythonsnippet
22 lines
import string

# string module constants: uppercase letters + digits make a 36-character code alphabet
ALPHABET = string.ascii_uppercase + string.digits

def normalize(code: str) -> str:
    # Strip separators and spaces, uppercase, then validate against the alphabet
    return code.replace("-", "").replace(" ", "").upper()

def is_valid(code: str) -> bool:
    return bool(code) and all(ch in ALPHABET for ch in code)

def format_code(code: str, group: int = 4) -> str:
    # Display in fixed groups so users can check the code character by character
    return "-".join(code[i : i + group] for i in range(0, len(code), group))

typed = "kx4r-9p2m ab"
clean = normalize(typed)
print("normalized:", clean)
print("valid:", is_valid(clean))
print("display:", format_code(clean))
print("rejects punctuation:", is_valid(normalize("ab#12")))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

normalized: KX4R9P2MAB
valid: True
display: KX4R-9P2M-AB
rejects punctuation: False

What the demo validates

ALPHABET joins string.ascii_uppercase and string.digits into the 36 legal redeem-code characters. normalize() strips dashes and spaces then uppercases, turning the typed input into KX4R9P2MAB before any check runs.

is_valid walks the cleaned code against the alphabet and prints True; the punctuation probe ab#12 fails because # has no place in the 36 characters. format_code regroups in fours with dashes so users can verify character by character.

Points worth noting

  • Normalize before validating, never the reverse.
  • Grouped display catches transcription slips early.

Interactive Tools for This Topic

FAQ

Why reject punctuation outright?
The alphabet is exactly 36 characters; any symbol in the cleaned code fails is_valid, as the printed False line for ab#12 shows.