Welcome, guest | Sign In | My Account | Store | Cart

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, 18 lines
 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 ;)

2 comments

sasa sasa 18 years, 11 months ago  # | flag

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
Jim Pryor 16 years, 2 months ago  # | flag

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

any(filename.endswith(x) for x in ('.jpg','.gif','.txt'))
Created by Michele Simionato on Tue, 29 Jul 2003 (PSF)
Python recipes (4591)
Michele Simionato's recipes (12)

Required Modules

  • (none specified)

Other Information and Tasks