3 回答
TA贡献1784条经验 获得超2个赞
这是一个正则表达式解决方案:
import re
bad_letters = "AKS"
word = "Sanctuary"
if re.search(f"[{bad_letters}]", word, re.IGNORECASE):
print("It is a match")
据称,这可能比避免使用正则表达式要慢。在这个例子中,这确实是正确的,但只是相当轻微。
$ python3 -mtimeit -s 'bad_letters = "AKSaks"; word = "Sanctuary"' 'any(char in word for char in bad_letters)'
1000000 loops, best of 3: 0.468 usec per loop
$ python3 -mtimeit -s 'bad_letters = "AKS"; word = "Sanctuary"; import re' 're.search(f"[{bad_letters}]", word, re.IGNORECASE)'
1000000 loops, best of 3: 0.622 usec per loop
事实上,测量的某些时间是'[AKS]'从坏字符构造模式'AKS'并编译正则表达式。如果将其从计时测量中剔除,那么预编译的正则表达式将轻松获胜。
$ python3 -mtimeit -s 'import re; bad_letters = "AKS"; matcher=re.compile(f"[{bad_letters}]", re.IGNORECASE).search; word = "Sanctuary"' 'matcher(word)'
10000000 loops, best of 3: 0.167 usec per loop
TA贡献1829条经验 获得超7个赞
我相信您想检查一个字符串中的错误字母,因此您可以执行以下操作:
word = "hello"
string = "EH"
for letter in string:
if letter.lower() in word.lower():
print('success')
else:
print('failure')
TA贡献1831条经验 获得超9个赞
如果您还想知道哪个字母匹配:
bad_letters="AKS".lower()
word="Sanctuary".lower()
for blet in bad_letters:
for let in word:
if blet==let:
print("It is a match:",let)
break
添加回答
举报