实现说明
全部逻辑都在函数 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")))