【问题标题】:Python: How can I check between two strings that have repeating letters if string 1 is contained within string 2?Python:如果字符串 1 包含在字符串 2 中,我如何检查两个具有重复字母的字符串?
【发布时间】:2020-09-29 10:08:40
【问题描述】:
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。

所以 'helo' 中的 'ell' 会返回 False 但是 'hello' 中的 'ell' 会返回 True

【问题讨论】:

标签: python string for-loop duplicates lowercase


【解决方案1】:

您可以使用in,但首先必须使案例相同:

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

【讨论】:

  • 这不适用于第一个示例。当你做print(can_spell_with('Ell','HEllo'))时,输出是False,当它为真时。
  • 应该是 "can_spell_with(letter_word, target_word)" 这是在做 "b in a" 而不是 "a in b"
  • 是的@Michael,这就是问题所在
  • 抱歉,我会解决的
【解决方案2】:

您正在执行不区分大小写的搜索。无需进行列表理解。只需使用lower()upper() 将所有字符转换为小写或大写并使用in

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

或者,您可以进行不区分大小写的正则表达式搜索:

import re

def can_spell_with(target_word, letter_word):
    return re.search(target_word, letter_word, re.IGNORECASE) is not None

【讨论】:

    【解决方案3】:

    这将检查 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
    

    【讨论】:

      【解决方案4】:
      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
      

      【讨论】:

      • 这部分是如何工作的:for i in range(len(letter_word)-lenn): if letter_word[i:i+lenn] == target_word: 它怎么知道'ell'和' helo' 'helo' 中没有第二个 'l' 吗?对我来说,它看起来像是在 helo 中搜索 e,然后在 helo 中搜索 l,然后在 helo 中搜索 l,结果是正确的
      【解决方案5】:

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

      【讨论】:

        猜你喜欢
        • 2017-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-19
        • 1970-01-01
        • 2012-04-21
        • 2016-07-20
        • 2020-12-12
        相关资源
        最近更新 更多