在Python中,如何检查字符串是否包含列表中的任何字符串?

时间:2015-08-20 14:51:37

标签: python string list blacklist

例如,where:

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

st包含来自admin的字符串list

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

这对黑名单很有用。

5 个答案:

答案 0 :(得分:7)

list = ['admin', 'add', 'swear']
st = 'siteadmin'
if any([x in st for x in list]):print "found"
else: print "not found"

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

答案 1 :(得分:1)

这是你在找什么?

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

答案 2 :(得分:1)

您可以使用list-comprehessions

来完成此操作
cudaSetDevice()

UPD: 你也想知道职位:

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

结果: [(' admin',4)

您可以在this page

上找到有关列表理解的更多信息

答案 3 :(得分:1)

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

#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

答案 4 :(得分:0)

for x in list:
     loc = st.find(x)
     if (loc != -1):
          print x
          print loc

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

这给出了知道在字符串中找到子字符串的位置的额外值。

相关问题