Slicing vs .startswith
Paul
wizard518 at aol.com
Mon Sep 22 18:39:00 EDT 2003
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?
Paul
Bob Gailer <bgailer at alum.rpi.edu> wrote in message news:<mailman.1064246454.19668.python-list at python.org>...
> At 09:17 AM 9/22/2003, Shu-Hsien Sheu wrote:
>
> >Hi,
> >
> >I have a question about the comparison of efficiency of string slicing and
> >using string.startswith.
> >For example, which one of the following would be more efficient, or ,
> >moreover, more pythonic?
> >
> >if aa[:3] == 'abc':
> >
> >vs
> >
> >if aa.startswith('abc'):
>
> Here's one way to address this kind of question:
>
> >>> import time
> >>> def f():
> ... st = time.time()
> ... for i in range(500000):
> ... if aa.startswith('abc'):pass
> ... print time.time() - st
> ...
> >>> f()
> 1.01200008392
> >>> def f():
> ... st = time.time()
> ... for i in range(500000):
> ... if aa[:3] == 'abc':pass
> ... print time.time() - st
> ...
> >>> f()
> 1.01100003719
>
> Bob Gailer
> bgailer at alum.rpi.edu
> 303 442 2625
>
> --
More information about the Python-list
mailing list