[英]Python: How can I check between two strings that have repeating letters if string 1 is contained within string 2?
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
In the code above: I am trying to figure out how to return True if the letter_word contains the target_word.在上面的代码中:我试图找出如果 letter_word 包含 target_word 时如何返回 True。
So 'ell' in 'helo' would return False But 'ell' in 'hello' would return True所以 'helo' 中的 'ell' 会返回 False 但 'hello' 中的 'ell' 会返回 True
Try to use in
:尝试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
You can use in
but you first have to make the cases the same:您可以使用in
但首先必须使大小写相同:
def can_spell_with(target_word, letter_word):
return target_word.lower() in letter_word.lower()
You're doing a case-insensitive search.您正在进行不区分大小写的搜索。 No need to do a list comprehension.无需进行列表理解。 Just use lower()
or upper()
to convert all characters to lower or uppercase and use in
:只需使用lower()
或upper()
将所有字符转换为小写或大写并in
使用:
def can_spell_with(target_word, letter_word):
return target_word.lower() in letter_word.lower()
Alternatively you could do a case insensitive regex search:或者,您可以进行不区分大小写的正则表达式搜索:
import re
def can_spell_with(target_word, letter_word):
return re.search(target_word, letter_word, re.IGNORECASE) is not None
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
this will check the whether word1 in word2 irrespective of lowercase or uppercase这将检查 word2 中的 word1 是否为小写或大写
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.