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

2024-04-19 07:21:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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

比如:

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

这段代码不起作用,只是为了显示我想要实现的目标。


Tags: oftheno字符串代码inifsome
3条回答

您可以使用^{}

if any(x in str for x in a):

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

如果您只想TrueFalse,那么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)

如果astr中的字符串变长,则应小心。直接解取O(S*(A^2)),其中Sstr的长度,A是a中所有字符串的长度之和。要获得更快的解决方案,请查看Aho-Corasick字符串匹配算法,该算法在线性时间O(S+a)中运行。

相关问题 更多 >