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

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

阅读 17.9k
7 个回答
if any(str_ in title for str_ in ("aaa", "bbb", "ccc")):
    print title

想麻烦了吧....

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

反了吧

if "aaa" in title or "bbb" in title or "ccc" in title :
    print title
  1. 用列表推导
def FindEx(str, modes):
    result = [mode in str  for mode in modes]
    return True in result

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

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

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

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

import re
if re.search('aaa|bbb|ccc,title):
    print "OK"
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题