Comparison problem

Peter Hansen peter at engcorp.com
Mon Nov 28 00:52:01 CET 2005


Fredrik Lundh wrote:
> Peter Hansen wrote:
>>Actually, it's not so much baroque as it is safe... item[0] will fail if
>>the string is empty, while item[0:1] will return '' in that case.
>>
>>Of course, as you point out, .startswith() is the better approach anyway.
> 
> $ timeit -s "s = 'abc'" "s[:1] == 'a'"
> 1000000 loops, best of 3: 0.852 usec per loop
> 
> $ timeit -s "s = 'abc'; w ='a'" "s[:len(w)] == w"
> 1000000 loops, best of 3: 1.27 usec per loop
> 
> $ timeit -s "s = 'abc'; c=s.startswith" "c('a')"
> 1000000 loops, best of 3: 1.75 usec per loop
> 
> $ timeit -s "s = 'abc'" "s.startswith('a')"
> 100000 loops, best of 3: 2.28 usec per loop

"Unless you have a need to optimize, in which case use timeit to find 
which approach works better.  If speed is not your primary concern, then 
.startswith() is probably the better approach since it is more readable 
to most people."

Thanks for the help with expanding on my original statement /F.  ;-)

-Peter




More information about the Python-list mailing list