在Python中,我如何检查一个字符串不包含列表中的任何字符串?

8
例如,在以下情况下:
list = [admin, add, swear]
st = 'siteadmin'

st 包含了来自 list 的字符串 admin

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

这对于黑名单来说非常有用。


我也想知道是哪个字符串,如果可能的话还想知道它在哪里,但那个答案绝对有帮助,谢谢。 - StringsOnFire
1
你可能需要使用正则表达式,因为你需要知道完整的单词匹配,以免将部分匹配误认为是错误的结果。例如,在判断'assertion' == True时忽略了 'ass' - Josh J
可以用正则表达式实现吗?就好像我需要一个白名单来检查是否发现了黑名单字符串... - StringsOnFire
1
不要将变量命名为“list”,这会与Python内置函数冲突。 - geher
5个回答

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

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


2
你可以通过使用列表推导式来完成这个操作。
ls = [item for item in lst if item in st]

更新:您还想知道位置:

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

结果: [('admin', 4)

你可以在这个页面找到更多关于列表推导式的信息。


ls = [item for item in lst if item in st] 这段代码是如何工作的? - StringsOnFire
@StringsOnFire 这被称为列表推导式。它意味着如果满足某个条件,则对列表中的每个项目执行某些操作。在这种情况下,条件是 st.find(item)!=-1。 - ig-melnyk

1
这是您正在寻找的吗?
for item in list:
    if item in st:
        print(item)
        break
    else:
        print("No string in list was matched")

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

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

string.find(i) 返回子字符串 i 在 st 中开始的索引,如果失败则返回-1。在我看来,这是最直观的答案,你可能可以将其简化为一行代码,但通常我不太喜欢那种方式。

这样做可以额外获得知道子字符串在字符串中的位置的价值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接