← 中文资源

简体中文版本

string 模块常量组成兑换码字符表

string.ascii_uppercase 加 string.digits 定义 36 个合法字符;先归一化(去分隔符、去空格、转大写)再校验,展示时按 4 位分组,方便用户逐字核对。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

全部逻辑都在函数 normalize、is_valid、format_code中。

使用要点

  • 演示输出是带标签的(normalized:、valid:、display:),每个操作都会留下自己的一行标注。
  • 把 normalize 当作 API:导入它,其余代码可以忽略。

常见问题

它依赖第三方库吗?

没有引用任何第三方库,标准库就够了。 文件在加载时定义 normalize、is_valid、format_code。

主要签名是 def normalize(code: str) -> str

核心语句

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))
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)

代码示例

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")))