Python:如何从列表中检查字符串中的子字符串? [英] Python: How to check a string for substrings from a list?
本文介绍了Python:如何从列表中检查字符串中的子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
检查另一个字符串中是否存在多个字符串
Possible Duplicate:
Check if multiple strings exist in another string
I can't seem to find an equivalent of code that functions like this anywhere for Python:
基本上,我想检查一个字符串是否包含列表中的子字符串.
Basically, I'd like to check a string for substrings contained in a list.
推荐答案
尝试此测试:
any(substring in string for substring in substring_list)
如果string
中包含任何substring_list
中的子字符串,它将返回True
.
It will return True
if any of the substrings in substring_list
is contained in string
.
Note that there is a Python analogue of Marc Gravell's answer in the linked question:
from itertools import imap
any(imap(s.__contains__, substring_list))
使用生成器表达式的上述版本可能更清晰.
Probably the above version using a generator expression is clearer though.
这篇关于Python:如何从列表中检查字符串中的子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文