Slicing vs .startswith

Peter Hansen peter at
Tue Sep 23 01:17:26 CEST 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':

That also handles the problem with files named "ThisFileIs.NotAjpg" 
being mistreated, as the other solutions do. ;-)


More information about the Python-list mailing list