ActiveState Code

Recipe 212959: Checking multiple endings


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)

Python
 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

Discussion

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 ;)

Comments

  1. 1. At 7:53 a.m. on 17 may 2005, sasa sasa said:

    A simpler approach.

    class endings( object ):
        """I compare equal to all suffixes of a given string.
        """
    
        def __init__( Self, String ):
            Self.String = String
    
        def __eq__( Self, Othr ):
            return Self.String.endswith( Othr )
    
    
    for filename in os.listdir('.')
        if endings(filename) in ( '.jpg', '.jpeg', '.gif' ):
            print filename
    
  2. 2. At 5:54 p.m. on 16 feb 2008, Jim Pryor said:

    Use any() in Python 2.5. This works in Python 2.5:

    any(filename.endswith(x) for x in ('.jpg','.gif','.txt'))
    

Sign in to comment