在字符串中查找数组项

7

我知道可以使用string.find()在字符串中查找子字符串。

但是,有没有一种最简单的方法可以在不使用循环的情况下查找数组项中是否有子字符串匹配字符串?

伪代码:

string = 'I would like an apple.'
search = ['apple','orange', 'banana']
string.find(search) # == True
3个回答

24
你可以使用一个生成器表达式(它某种程度上就是一个循环)。
any(x in string for x in search)
生成器表达式是括号内的部分,它创建一个可迭代对象,对于元组search中的每个x,返回x in string的值。 x in string进而返回string是否包含子字符串x。最后,Python内置函数any()遍历传递给它的可迭代对象,并返回其中任何一个项是否为True
另外,您可以使用正则表达式来避免循环:
import re
re.search("|".join(search), string)

我会选择第一个解决方案,因为正则表达式有一些缺陷(如转义等)。


2
生成器表达式加 1 分。正则表达式减 1 分。建议不使用正则表达式再加 1 分。好极了!加 1 分! - nmichaels
@nmichaels:我只包含正则表达式示例,因为它符合“无循环”要求。 - Sven Marnach
@Sven:我明白了。我的话有点玩笑,但这是一个很好的答案。 - nmichaels
为了消除在 search 中一些字符可能存在的符号意义,根据 re 的规则,可以这样做:re.search("|".join(re.escape(search)), string)。那么还有哪些陷阱需要注意呢? - eyquem
@eyquem:在这个特定的例子中,转义可能是唯一的陷阱。 - Sven Marnach
@Sven Marnach 好的。顺便说一下,我点赞是因为你给出了更简单的答案,并且提到了正则表达式。 - eyquem

3

Python中的字符串是序列,您可以通过查询一个字符串是否存在于另一个字符串中来进行快速成员测试:

>>> mystr = "I'd like an apple"
>>> 'apple' in mystr
True

Sven 的第一个回答是正确的。要检查某个字符串中是否存在多个字符串中的任意一个,可以使用以下代码:

>>> ls = ['apple', 'orange']
>>> any(x in mystr for x in ls)
True

值得注意的是,以后参考时内置的 'all()' 函数只有在 'ls' 中的 所有 项目都是 'mystr' 的成员时才会返回 true:
>>> ls = ['apple', 'orange']
>>> all(x in mystr for x in ls)
False
>>> ls = ['apple', 'like']
>>> all(x in mystr for x in ls)
True

1

最简单的是

import re
regx = re.compile('[ ,;:!?.:]')

string = 'I would like an apple.'
search = ['apple','orange', 'banana']

print any(x in regx.split(string) for x in search)

编辑

纠正,在阅读了Sven的答案之后:显然,字符串不能被分割,太愚蠢了!any(x in string for x in search)非常有效

如果你不想使用循环:

import re
regx = re.compile('[ ,;:!?.:]')

string = 'I would like an apple.'
search = ['apple','orange', 'banana']
print regx.split(string)

print set(regx.split(string)) & set(search)

结果

set(['apple'])

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