scanf style parsing

Stefan Schwarzer s.schwarzer at ndh.net
Sat Sep 29 11:05:51 EDT 2001


Hello Tim

Tim Hammerquist wrote:
> > > or, much more preferably:
> > >
> > >     if filename[-4:] == '.txt':
> > >         ...
> >
> > Since (I think:) Python 2.0 it's possible to use
> >
> > if filename.endswith('.txt'):
> >     ...
> >
> > which is less error-prone if the string is a bit longer.
> 
> ..and much more maintainable. You no longer must change the index when
> the length of the string changes.

Yes, I meant that by "less error-prone". Up to four characters are yet 
_relatively_ simply to see, but with more characters it is easy to mismatch
the string and the number.

Because endswith exists, this is the better solution, of course. But otherwise,
it could anyhow also be defined like

def endswith(s, part):
    return s[ -len(part) : ] == part

> Very nice.  I hadn't been
> familiarized with this method.  Thank you for bringing it up.

:-)

Stefan



More information about the Python-list mailing list