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.
Code
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: FalseWhat 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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.