检查多个字符串是否存在于另一个字符串中

646 投票
19 回答
715483 浏览
提问于 2025-04-16 02:12

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

举个例子:

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")

我该如何替换 if a in s: 这一行,以得到正确的结果呢?

19 个回答

118

any() 是一种非常好的方法,如果你只想知道结果是 True 还是 False。但是如果你想具体知道哪些字符串匹配,可以使用一些其他的方法。

如果你想找到第一个匹配的字符串(默认是 False):

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

如果你想找到所有匹配的字符串(包括重复的):

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

如果你想找到所有不重复的匹配字符串(不考虑顺序):

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

如果你想找到所有不重复的匹配字符串,并保持正确的顺序:

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

你可以使用 any 这个函数:

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

撰写回答