【问题标题】:Python for loop in avoid similar matchPython for 循环避免类似匹配
【发布时间】:2012-05-28 14:20:52
【问题描述】:

考虑以下列表:

items = ['about-conference','conf']

使用以下 for 循环对列表进行迭代,打印“about-conference”和“conf”

for word in items:
    if 'conf' in word:
        print word

如何让 if 语句仅在遇到完全匹配时才证明为真,即仅打印“conf”?

谢谢。

【问题讨论】:

    标签: python for-loop match


    【解决方案1】:

    不要使用in,使用== 来测试是否完全相等:

    if word == "conf":
       print word
    

    【讨论】:

      【解决方案2】:

      您可以执行以下操作:

      for word in list:
          if 'conf' == word.strip():
              print(word)
      

      剥离确保没有空格或行尾等虚假字符。

      【讨论】:

        【解决方案3】:

        不完全确定你想要什么,但如果你正在寻找这样的东西,它使用单词边界,所以它由破折号、空格、字符串开头等分隔。

        import re
        for word in items:
            if 'conf' in re.findall(r'\b\w+\b', word):
                print 'conf'
        

        【讨论】:

          【解决方案4】:

          试试这个:

          for word in list:
              if word == 'conf':
                  print word
          

          【讨论】:

            【解决方案5】:

            在这个具体示例中,您可以将其重写为:

            items = ['about-conference','conf']
            if 'conf' in items:
                print 'conf'
            

            【讨论】:

              猜你喜欢
              • 2017-08-27
              • 2017-11-11
              • 1970-01-01
              • 2022-01-04
              • 1970-01-01
              • 1970-01-01
              • 2023-03-27
              • 2012-06-25
              • 2020-03-10
              相关资源
              最近更新 更多