首页 > Python:判断是否包含指定字符串的代码简化

Python:判断是否包含指定字符串的代码简化

if title.find("aaa")>=0 or title.find("bbb")>=0 or title.find("ccc")>=0:
    print title

请问,以上代码如何简化呢?

if title in ["aaa","bbb","ccc"]:
    print title

这样肯定是不行的,不知道可以如何简化呢?
注:我想事先创建个字符串数组,其中包含要过滤的短语


if filter(lambda x: x in title, ['aaa','bbb','ccc']):
print title


反了吧

if "aaa" in title or "bbb" in title or "ccc" in title :
    print title

想麻烦了吧....

if [s for s in ['aaa','bbb','ccc'] if s in title]: print title

if any(str_ in title for str_ in ("aaa", "bbb", "ccc")):
    print title

  1. 用列表推导
def FindEx(str, modes):
    result = [mode in str  for mode in modes]
    return True in result

你也可以把这整合成一句代码
2. 用正则表达式


我觉得每个人都有自己的使用习惯,上面的方法都可以,看自己个人喜好喽,当然至于有木有涉及到效率问题,就木有研究哈,偶是python新人。

import re
if re.search('aaa|bbb|ccc,title):
    print "OK"

用正则?其实吧别简化了,就这样也不错。

【热门文章】
【热门文章】