【问题标题】:How to check a string does not contain two different substrings with only one condition?如何检查一个字符串不包含只有一个条件的两个不同的子字符串?
【发布时间】:2021-08-22 06:11:34
【问题描述】:

我有一个名为 name 的字符串。我对名称既不包含'bias' 也不包含'bn' 的情况感兴趣。我可以通过以下两种方式使用两个条件来实现它:

if 'bias' not in name and 'bn' not in name:
   pass

或者使用德摩根定律如下:

if not ('bias' in name or 'bn' in name):
   pass

请注意,名称的字符数比 'bias''bn' 多,因此我们不能将 name not in {'bias', bn'} 作为单条件情况。

问题:我们如何检查名称字符串是否既不包含'bias' 也不包含'bn' 一个in 或一个条件?

【问题讨论】:

    标签: python if-statement


    【解决方案1】:

    您可以创建要搜索的子字符串列表,基本上循环遍历列表,并使用in 检查它是否是输入字符串的一部分。

    name = 'some name'
    to_search = ['bias', 'bn']
    found_a_string = False
    for item in to_search:
        if item in name:
            print(item, 'is a part of ', name)
            found_a_string = True
    
    if found_a_string:
        print("Present")
    else:
        print("NA")
    

    使用any

    name = 'some name'
    to_search = ['bias', 'bn']
    
    if any(x in name for x in to_search):
        print("Present")
    else:
        print("No matches found")
    

    【讨论】:

    • 任何你想要的。@Sepide
    【解决方案2】:

    使用refindall,返回匹配的列表:

    import re
    if len(re.findall('bias|bn', name)) == 0:
        pass
    

    【讨论】:

      【解决方案3】:

      我们可以尝试使用re.search 和列表推导:

      inp = ["a bias", "a bn", "a bn bias", "other"]
      output = ["MATCH" if re.search(r'^(?!.*bias)(?!.*bn)\w+$', x) else "NO MATCH" for x in inp]
      print(output)  # ['NO MATCH', 'NO MATCH', 'NO MATCH', 'MATCH']
      

      下面是正则表达式模式的解释:

      ^               from the start of the input string
          (?!.*bias)  assert that the substring "bias" appears nowhere
          (?!.*bn)    assert that the substring "bn" appears nowhere
          \w+         then match any word
      $               end of the input
      

      【讨论】:

        【解决方案4】:

        试试这个:

        name = 'An string'
        if False in [i not in name for i in ['bias', 'bn']]:
            print('Yes')
        

        你也可以创建一个函数来让它更简单:

        def IsTrueName(name):
            return False in [i not in name for i in ['bias', 'bn']]
        
        name = 'An string'
        if IsTrueName(name):
            print('Yes')
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-02-26
          • 1970-01-01
          • 2021-05-06
          • 1970-01-01
          • 2023-03-31
          • 2013-03-13
          • 1970-01-01
          • 2022-12-30
          相关资源
          最近更新 更多