Slicing vs .startswith

Peter Hansen peter at engcorp.com
Mon Sep 22 19:17:26 EDT 2003


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

-Peter




More information about the Python-list mailing list