验证魔法咒语
作为最后的挑战,我们将验证用于给魔杖施加魔法的咒语。咒语必须遵循严格的模式:它们必须以一个魔法词开头,接着是一个冒号,然后是一系列用逗号分隔的魔法参数或咒语。一个有效的魔法咒语看起来像 'Lumos:maxima,solemnly,nova'。
在 ~/project
目录中打开 enchantment_validator.py
,并编写一个函数,使用正则表达式来验证一系列魔法咒语。
import re
def validate_enchantment(phrase):
## 用于匹配有效魔法咒语的正则表达式模式
pattern = r"^[A-Za-z]+:(?:[A-Za-z]+,)*[A-Za-z]+$"
if re.fullmatch(pattern, phrase):
return True
else:
return False
## 要验证的咒语列表
phrases = [
"Lumos:maxima,solemnly,nova",
"Reducio:shrink,less",
"Protego:maxima",
"Alohomora:",
"Expelliarmus:disarm,fight,duel,"
]
## 验证每个咒语
for phrase in phrases:
result = validate_enchantment(phrase)
print(f"'{phrase}' 是 {'有效' if result else '无效'}")
运行代码并检查验证结果。
python enchantment_validator.py
预期输出应显示哪些咒语是有效的:
'Lumos:maxima,solemnly,nova' 是有效
'Reducio:shrink,less' 是有效
'Protego:maxima' 是有效
'Alohomora:' 是无效
'Expelliarmus:disarm,fight,duel,' 是无效