feature request: a better str.endswith

Michele Simionato mis6 at pitt.edu
Sat Jul 19 09:29:41 EDT 2003


Irmen de Jong <irmen at -NOSPAM-REMOVETHIS-xs4all.nl> wrote in message news:<3f17f883$0$49107$e4fe514c at news.xs4all.nl>...
> Jp Calderone wrote:
> > On Fri, Jul 18, 2003 at 05:01:47AM -0700, Michele Simionato wrote:
> > 
> >>I often feel the need to extend  the string method ".endswith" to tuple
> >>arguments, in such a way to automatically check for multiple endings.
> >>For instance, here is a typical use case:
> >>
> >>if filename.endswith(('.jpg','.jpeg','.gif','.png')):
> >>    print "This is a valid image file"
> >>
> >>Currently this is not valid Python and I must use the ugly
> >>
> >>if filename.endswith('.jpg') or filename.endswith('.jpeg') \
> >>   or filename.endswith('.gif') or filename.endswith('.png'):
> >>    print "This is a valid image file"
> > 
> > 
> >     extensions = ('.jpg', '.jpeg', '.gif', '.png')
> >     if filter(filename.endswith, extensions):
> >         print "This is a valid image file
> > 
> >   Jp
> > 
> 
> Using filter Michele's original statement becomes:
> 
> if filter(filename.endswith, ('.jpg','.jpeg','.gif','.png')):
>      print "This is a valid image file"
> 
> IMHO this is simple enough to not require a change to the
> .endswith method...
> 
> --Irmen

I haven't thought of "filter". It is true, it works, but is it really
readable? I had to think to understand what it is doing.
My (implicit) rationale for

filename.endswith(('.jpg','.jpeg','.gif','.png'))

was that it works exactly as "isinstance", so it is quite
obvious what it is doing. I am asking just for a convenience,
which has already a precedent in the language and respects 
the Principle of Least Surprise.

                       Michele




More information about the Python-list mailing list