Comparison problem
Fredrik Lundh
fredrik at pythonware.com
Sun Nov 27 05:51:51 EST 2005
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
</F>
More information about the Python-list
mailing list