我需要检查组成给定单词的所有字母是否都包含在给定字符串中。我试过一些东西,但不起作用:
def check(texto, control):
for letra in control:
if texto.find(letra) == control.find(letra):
return control + " is not here"
else:
return control + " is here!"
打印检查('jshdgfyrgj','Correo')
应返回"Correo不在"
打印检查('cfgotyrtepo','Correo')
应该返回"Correo在这里!"
它目前返回correo在所有情况下都在这里。我的代码出了什么问题?谢谢
有两个问题-第一,您希望函数忽略大小写差异,但不要告诉它这样做。-"c"不是"c"。
为了检查字母是否在字符串中,通常最好使用letter in text_string
而不是str.find()
方法。确保您了解查找退货的内容-查看文档。
在下面的例子中,我使用letter in set(text_string)
——如果有重复的话,这只会检查text_string
的字母一次。对于小字符串来说,这不会对性能产生太大影响。
您可以使用all
函数来执行一系列布尔检查。
def check(text, control):
# Set both strings to lower case, since we're ignoring case
text = text.lower()
control = control.lower()
# Check that each character in control is in text
return all((c in text for c in set(control)))
>>> check('jshdgfyrgj', 'Correo')
2: False
>>> check('cfgotyrrtepo', 'Correo')
3: True
为什么不做一些类似的事情:
def check(texto, control):
texto = [letter for letter in texto]
while texto:
for letra in control:
if letra in texto:
texto.remove(letra)
else:
return False
return True
这确保了重复的字母也在texto中重复。
例如
>>> check('abc','bac')
True
>>> check('abc','bacc')
False
如果订单无关紧要:
...
return all([letter in texto for letter in control])
如果订单很重要:
...
texto_modified = "".join([letter for letter in texto if letter in control])
return texto_modified == control