查找字符串中的数组项
我知道可以使用 string.find() 来查找字符串中的子字符串。
但是,在不使用循环的情况下找出数组项之一是否在字符串中具有子字符串匹配的最简单方法是什么?
伪代码:
string = 'I would like an apple.'
search = ['apple','orange', 'banana']
string.find(search) # == True
I know can use string.find()
to find a substring in a string.
But what is the easiest way to find out if one of the array items has a substring match in a string without using a loop?
Pseudocode:
string = 'I would like an apple.'
search = ['apple','orange', 'banana']
string.find(search) # == True
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用生成器表达式(它在某种程度上是一个循环)
生成器表达式是括号内的部分。它创建一个迭代器,为元组
search
中的每个x
返回x in string
的值。x in string
依次返回string
是否包含子字符串x
。最后,Python 内置any()
迭代它所传递的可迭代对象,如果其任何项的计算结果为 True,则返回。或者,您可以使用正则表达式来避免循环:
我会选择第一个解决方案,因为正则表达式有陷阱(转义等)。
You could use a generator expression (which somehow is a loop)
The generator expression is the part inside the parentheses. It creates an iterable that returns the value of
x in string
for eachx
in the tuplesearch
.x in string
in turn returns whetherstring
contains the substringx
. Finally, the Python built-inany()
iterates over the iterable it gets passed and returns if any of its items evaluate toTrue
.Alternatively, you could use a regular expression to avoid the loop:
I would go for the first solution, since regular expressions have pitfalls (escaping etc.).
Python 中的字符串是序列,您可以通过询问一个字符串是否存在于另一个字符串中来进行快速成员资格测试:
Sven 在上面的第一个答案中得到了正确的答案。要检查其他字符串中是否存在任何多个字符串,您可以这样做:
值得注意的是,供将来参考的是,内置的“all()”函数仅当 all 项在“ls”是“mystr”的成员:
Strings in Python are sequences, and you can do a quick membership test by just asking if one string exists inside of another:
Sven got it right in his first answer above. To check if any of several strings exist in some other string, you'd do:
Worth noting for future reference is that the built-in 'all()' function would return true only if all items in 'ls' were members of 'mystr':
更简单的是
编辑
更正,在阅读斯文的答案后:显然,字符串必须不被分割,愚蠢的!
any(x in string for x in search)
效果很好如果你不想循环:
结果
The simpler is
EDIT
Correction, after having read Sven's answer: evidently, string has to not be splited, stupid !
any(x in string for x in search)
works pretty wellIf you want no loop:
result