Python: 我如何在两个有重复字母的字符串之间检查字符串1是否包含在字符串2中?

问题描述 投票:0回答:1
    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。

python string for-loop duplicates lowercase
1个回答
2
投票

尝试使用 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

2
投票

你在做一个不区分大小写的搜索。不需要做一个列表理解。只要使用 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

2
投票

你可以使用 in 但你首先要使大小写相同。

def can_spell_with(target_word, letter_word):
    return target_word.lower() in letter_word.lower()

1
投票
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

1
投票

这将检查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
© www.soinside.com 2019 - 2024. All rights reserved.