如何检查数组中的任何字符串是否存在于另一个字符串中?

例如:

a = ['a', 'b', 'c']
s = "a123"
if a in s:
    print("some of the strings found in s")
else:
    print("no strings found in s")

我如何替换如果a在s:行得到适当的结果?


当前回答

只是关于如何在String中获得所有列表元素的更多信息

a = ['a', 'b', 'c']
str = "a123" 
list(filter(lambda x:  x in str, a))

其他回答

你可以使用任何:

a_string = "A string is more than its parts!"
matches = ["more", "wholesome", "milk"]

if any([x in a_string for x in matches]):

类似地,要检查是否找到列表中的所有字符串,请使用all而不是any。

的元素上进行迭代。

a = ['a', 'b', 'c']
str = "a123"
found_a_string = False
for item in a:    
    if item in str:
        found_a_string = True

if found_a_string:
    print "found a match"
else:
    print "no match found"

如果你想要的只是True或False, any()是目前为止最好的方法,但如果你想知道具体匹配哪个字符串/字符串,你可以使用一些东西。

如果你想要第一个匹配(默认为False):

match = next((x for x in a if x in str), False)

如果你想获得所有匹配项(包括重复项):

matches = [x for x in a if x in str]

如果你想获得所有非重复的匹配(不考虑顺序):

matches = {x for x in a if x in str}

如果你想按正确的顺序获得所有非重复的匹配项:

matches = []
for x in a:
    if x in str and x not in matches:
        matches.append(x)

为了增加regex的多样性:

import re

if any(re.findall(r'a|b|c', str, re.IGNORECASE)):
    print 'possible matches thanks to regex'
else:
    print 'no matches'

或者如果你的列表太长- any(re.findall(r'|'.join(a), str, re.IGNORECASE))

flog = open('test.txt', 'r')
flogLines = flog.readlines()
strlist = ['SUCCESS', 'Done','SUCCESSFUL']
res = False
for line in flogLines:
     for fstr in strlist:
         if line.find(fstr) != -1:
            print('found') 
            res = True


if res:
    print('res true')
else: 
    print('res false')