def can_spell_with(target_word, letter_word):
valid = True
target_word1 = [x.lower() for x in target_word]
letter_word1 = [x.lower() for x in letter_word]
for c in target_word1:
if c not in letter_word1:
valid = False
else:
valid = True
return valid
print(can_spell_with('elL','HEllo'))
# True
print(can_spell_with('ell','helo'))
# False
在上面的代码中,我想知道如何在letter_word包含target_word的情况下返回True。我想知道如何在letter_word包含target_word的情况下返回True.
所以'helo'中的'ell'将返回False,但'hello'中的'ell'将返回True。
尝试使用 in
:
def can_spell_with(a, b):
return (a.upper() in b.upper())
print(can_spell_with('Ell','HEllo'))
>>>True
print(can_spell_with('ell','helo'))
>>>False
你在做一个不区分大小写的搜索。不需要做一个列表理解。只要使用 lower()
或 upper()
将所有字符转换为小写或大写,并使用 in
:
def can_spell_with(target_word, letter_word):
return target_word.lower() in letter_word.lower()
另外,你也可以进行不区分大小写的regex搜索。
import re
def can_spell_with(target_word, letter_word):
return re.search(target_word, letter_word, re.IGNORECASE) is not None
你可以使用 in
但你首先要使大小写相同。
def can_spell_with(target_word, letter_word):
return target_word.lower() in letter_word.lower()
target_word = target_word.lower()
letter_word = letter_word.lower()
lenn = len(target_word)
valid = False
for i in range(len(letter_word)-lenn):
if letter_word[i:i+lenn] == target_word:
valid = True
return valid
这将检查word1是否在word2中 不管是小写还是大写。
def func(word1, word2):
first_char = word1[0]
for index, char in enumerate(word2):
if char==first_char:
if word2[index:len(word1)+1]==word1:
return True
return False