Slicing vs .startswith
David Eppstein
eppstein at ics.uci.edu
Mon Sep 22 19:35:39 EDT 2003
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'
It may be a little longer than the other solutions, but it expresses the
meaning more clearly.
--
David Eppstein http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science
More information about the Python-list
mailing list