在Python中,如何检查字符串是否不包含列表中的任何字符串?
例如,其中:在Python中,如何检查字符串是否不包含列表中的任何字符串?,python,string,list,blacklist,Python,String,List,Blacklist,例如,其中: list = [admin, add, swear] st = 'siteadmin' st包含列表中的字符串admin 如何执行此检查 如何告知我找到了列表中的哪个字符串,如果可能,在哪里(从开始到结束以突出显示有问题的字符串) 这对黑名单很有用。这就是你要找的吗 for item in list: if item in st: print item break else: print "No string in list w
list = [admin, add, swear]
st = 'siteadmin'
st
包含列表中的字符串admin
- 如何执行此检查
- 如何告知我找到了
列表中的哪个字符串,如果可能,在哪里(从开始到结束以突出显示有问题的字符串)
这对黑名单很有用。这就是你要找的吗
for item in list:
if item in st:
print item
break
else:
print "No string in list was matched"
find(i)返回substr i在st中开始的位置的索引,或者失败时返回-1。在我看来,这是最直观的答案,你可以把它做成一行,但我通常不太喜欢
这为知道子字符串在字符串中的位置提供了额外的价值 您可以使用列表压缩来完成此操作
ls = [item for item in lst if item in st]
UPD:
您还想知道位置:
ls = [(item,st.find(item)) for item in lst if st.find(item)!=-1]
结果:
[('admin',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
您可以使用任何内置函数来检查列表中的任何字符串是否出现在目标字符串中我也想知道它是哪一个字符串,如果可能的话,它在哪里,但是这个答案仍然非常有用,谢谢您可能需要正则表达式,因为您需要知道完整的单词匹配,以便部分匹配sn不被视为假阳性。例如,在“断言”中忽略'ass'==True
这可以在正则表达式中完成吗?这几乎就像我需要一个白名单来检查何时发现黑名单字符串…不要将变量命名为“list”,它与内置python冲突。ls=[item For item in lst if item in st]
work?@StringsOnFire这称为列表理解。它意味着如果某个条件成立,则对列表中的每个项目执行一些操作。在这种情况下,条件是st.find(item)!=-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
list = ['admin', 'add', 'swear']
st = 'siteadmin'
if any([x in st for x in list]):print "found"
else: print "not found"