Recipe 1.19. Checking a String for Any of Multiple EndingsCredit: Michele Simionato ProblemFor a certain string s, you must check whether s has any of several endings; in other words, you need a handy, elegant equivalent of s.endswith(end1) or s.endswith(end2) or s.endswith(end3) and so on. SolutionThe itertools.imap function is just as handy for this task as for many of a similar nature: import itertools def anyTrue(predicate, sequence): return True in itertools.imap(predicate, sequence) def endsWith(s, *endings): return anyTrue(s.endswith, endings) DiscussionA typical use for endsWith might be to print all names of image files in the current directory: import os for filename in os.listdir('.'): if endsWith(filename, '.jpg', '.jpeg', '.gif'): print filename The same general idea shown in this recipe's Solution is easily applied to other tasks related to checking a string for any of several possibilities. The auxiliary function anyTrue is general and fast, and you can pass it as its first argument (the predicate) other bound methods, such as s.startswith or s._ _contains_ _. Indeed, perhaps it would be better to do without the helper function endsWithafter all, directly coding if anyTrue(filename.endswith, (".jpg", ".gif", ".png")): seems to be already readable enough.
This recipe originates from a discussion on news:comp.lang.python. and summarizes inputs from many people, including Raymond Hettinger, Chris Perkins, Bengt Richter and others. See AlsoLibrary Reference and Python in a Nutshell docs for itertools and string methods. |