Slicing vs .startswith
xtian at toysinabag.com
Mon Sep 22 23:47:51 CEST 2003
David Eppstein <eppstein at ics.uci.edu> wrote in message news:<eppstein-89A196.11515122092003 at news.service.uci.edu>...
> In article <3F6F3E38.5221D7E7 at engcorp.com>,
> Peter Hansen <peter at engcorp.com> wrote:
> > > For example, which one of the following would be more efficient, or ,
> > > moreover, more pythonic?
> > >
> > > if aa[:3] == 'abc':
> > >
> > > vs
> > >
> > > if aa.startswith('abc'):
> > The latter is clearly more readable.
> More Pythonic, too, I think. "Readability counts," and "There should be
> one-- and preferably only one --obvious way to do it." In this case,
> startswith must be the one obvious way, or else why would it exist in
> the standard library at all?
It's also much more maintainable - if in the future that 'abc' needs
to change to 'abcdef', the slicing version requires changes in two
places (just asking for bugs), while startswith requires only one. Of
course, all these things (readability, maintainability and
pythonicism) are fairly closely interrelated.
More information about the Python-list