Recipe 1.19. Checking a String for Any of Multiple Endings
Credit: Michele
Simionato
Problem
For 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.
Solution
The 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)
Discussion
A typical use for endsWith might be to print all
names of image files in the current directory:
import osThe same general idea shown in this recipe's
for filename in os.listdir('.'):
if endsWith(filename, '.jpg', '.jpeg', '.gif'):
print filename
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.
See Also
Library Reference and Python in a
Nutshell docs for itertools and string
methods.