Slicing vs .startswith
Fredrik Lundh
fredrik at pythonware.com
Wed Sep 24 17:48:44 EDT 2003
RE: Slicing vs .startswithFacundo Batista wrote:
See PEP 08:
- Avoid slicing strings when checking for prefixes or suffixes.
Use startswith() and endswith() instead, since they are faster,
cleaner and less error prone. E.g.:
No: if foo[:3] == 'bar':
Yes: if foo.startswith('bar'):
The exception is if your code must work with Python 1.5.2 (but
let's hope not!).
the PEP isn't telling the truth:
> python timeit.py -s "s='egg&bacon'" "s[:3] == 'egg'"
100000 loops, best of 3: 4.43 usec per loop
> python timeit.py -s "s='egg&bacon'" "s.startswith('egg')"
100000 loops, best of 3: 7.6 usec per loop
</F>
More information about the Python-list
mailing list