检查多个字符串是否存在于另一个字符串中
我该如何检查一个数组中的任何字符串是否存在于另一个字符串中呢?
举个例子:
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)