【问题标题】:In Python, how can I check that a string does not contain any string from a list?在 Python 中,如何检查字符串是否不包含列表中的任何字符串?
【发布时间】:2015-11-14 06:56:05
【问题描述】:

例如,其中:

list = [admin, add, swear]
st = 'siteadmin'

st 包含来自list 的字符串admin

  • 如何执行此检查?
  • 如何得知找到了来自list 的哪个字符串,以及如果可能的话在哪里(从开始到结束以突出显示有问题的字符串)?

这对黑名单很有用。

【问题讨论】:

  • 我也想知道它是哪个字符串,如果可能的话,它在哪里,但这个答案仍然很有帮助,谢谢
  • 您可能需要正则表达式,因为您需要知道完整的单词匹配,以便不将部分匹配视为误报。例如忽略'ass' in 'assertion' == True
  • 可以在正则表达式中完成吗?这几乎就像我需要一个白名单来检查何时找到列入黑名单的字符串......
  • 不要将变量命名为'list',它与内置的python冲突。

标签: python string list blacklist


【解决方案1】:

这是你要找的吗?

for item in list:
    if item in st:
        print(item)
        break
    else:
        print("No string in list was matched")

【讨论】:

    【解决方案2】:
    for x in list:
         loc = st.find(x)
         if (loc != -1):
              print x
              print loc
    

    string.find(i) 返回 substr i 在 st 中开始的索引,如果失败则返回 -1。在我看来,这是最直观的答案,你可以把它做成一个 1 班轮,但我通常不是这些班轮的忠实粉丝。

    这提供了知道子字符串在字符串中的位置的额外价值。

    【讨论】:

      【解决方案3】:

      您可以通过使用 list-comprehessions 来做到这一点

      ls = [item for item in lst if item in st]
      

      更新: 你也想知道位置:

      ls = [(item,st.find(item)) for item in lst if st.find(item)!=-1]
      

      结果: [('管理员', 4)

      你可以在this page找到更多关于列表理解的信息

      【讨论】:

      • ls = [item for item in lst if item in st] 是如何工作的?
      • @StringsOnFire 这称为列表理解。这意味着如果某些条件成立,则对列表中的每个项目进行一些操作。在这种情况下,条件是 st.find(item)!=-1。
      【解决方案4】:

      我假设列表非常大。所以在这个程序中,我将匹配的项目保存在一个列表中。

      #declaring a list for storing the matched items
      matched_items = []
      #This loop will iterate over the list
      for item in list:
          #This will check for the substring match
          if item in st:
              matched_items.append(item)
      #You can use this list for the further logic
      #I am just printing here 
      print "===Matched items==="
      for item in matched_items:
          print item
      

      【讨论】:

        【解决方案5】:
        list = ['admin', 'add', 'swear']
        st = 'siteadmin'
        if any([x in st for x in list]):print "found"
        else: print "not found"
        

        您可以使用任何内置函数来检查列表中的任何字符串是否出现在目标字符串中

        【讨论】:

          猜你喜欢
          • 2012-11-15
          • 2020-08-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-24
          • 2020-02-26
          • 2014-07-08
          • 2014-08-09
          相关资源
          最近更新 更多