Slicing vs .startswith

Peter Hansen peter at engcorp.com
Tue Sep 23 02:19:59 CEST 2003


David Eppstein wrote:
> 
> In article <3F6F8306.1ABCC6D at engcorp.com>,
>  Peter Hansen <peter at engcorp.com> wrote:
> 
> > Paul wrote:
> > >
> > > However, what if you don't want case sensitivity?  For example, to
> > > check if a file is a jpg, I do name[-3:].lower() == 'jpg'.  This will
> > > work with both foo.jpg and foo.JPG.
> > >
> > > Is this slower than name.lower().endswith('jpg')?  Is there a better
> > > solution altogether?
> >
> > Yes, of course. :-)
> >
> > import os
> > if os.path.splitext(name)[1].lower() == 'jpg':
> >     pass
> >
> > That also handles the problem with files named "ThisFileIs.NotAjpg"
> > being mistreated, as the other solutions do. ;-)
> 
> I was about to post the same answer.  One minor nit, though: it should be
> 
> os.path.splitext(name)[1].lower() == '.jpg'

Oops, thanks!  I _always_ make that mistake.  It just seems that if 
os.path.split() does not return any path separators in the components,
then os.path.splitext() shouldn't return the extension separator...

Luckily we have tests around here to catch that kind of thing. :-)

-Peter




More information about the Python-list mailing list