给定一个字符串s,检查s是否含有多个结束标记中的一个。
import itertools
def anyTrue(predicate, sequence):
return True in itertools.imap(predicate, sequence)
def endsWith(s, *endings):
return anyTrue(s.endswith, endings)
一个典型应用:
打印出当前目录中所有的图片文件
import os
for filename in os.listdir('.'):
if endsWith(filename, '.jpg', '.jpeg', '.gif'):
print filename
或者
import os
for filename in os.listdir('.'):
if anyTrue(filename, ('.jpg', '.jpeg', '.gif')):
print filename
python endswith()源码:
def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
"""
S.endswith(suffix[, start[, end]]) -> bool
Return True if S ends with the specified suffix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
suffix can also be a tuple of strings to try.
"""
return False
doc最后一句中指出,suffix可以为字符串构成tuple,于是:
prefix_list = tuple(u'是 词 拼 结束 状态 抓取 百度 词频'.split())
s = u'只要词频抓取为结束状态'
print s.endswith(prefix_list) #True
而且作为内建函数,速度优于
itertools.imap(predicate, sequence)