A short idiom for s.endswith(ending1) or s.endswith(ending2) or s.endswith(ending3) or ... Shows the goodies of the Python 2.3 itertools module and summarizes a discussion on c.l.py (thread "a better str.endswith", July 2003)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | """Credits:
Raymond Hettinger suggested using itertools
Chris Perkins suggested using itertools.imap
Bengt Richter suggested the name any_true
many others gave useful input on c.l.py
I did cut and paste ;)"""
import os,itertools
def anyTrue(pred,seq):
"Returns True if a True predicate is found, False
otherwise. Quits as soon as the first True is found"
return True in itertools.imap(pred,seq)
# example: print image files in the current directory
the=anyTrue # for readability
for filename in os.listdir('.'):
if the(filename.endswith,('.jpg','.jpeg','.gif')):
print filename
|
It is quite common to have to check for multiple endings of a string, for instance to list all the image files in a directory, or in sorting problems. The interest of this recipe is to show the goodies of the new itertools module, available in Python 2.3 and that deserves to be better known ;)
A simpler approach.
Use any() in Python 2.5. This works in Python 2.5: