can it be shorter?

Scott David Daniels Scott.Daniels at Acm.Org
Sat Jun 6 18:28:16 EDT 2009


kj wrote:
> ... And actually, if speed is the criterion, then one should also avoid endswith:
> 
>>>> from timeit import Timer
>>>> min(Timer("if s[-1] != '/': s += '/'", "s = 'abcd/efgh'").repeat())
> 0.18654584884643555
>>>> min(Timer("if not s.endswith('/'): s += '/'", "s = 'abcd/efgh'").repeat())
> 0.43395113945007324

_but_, try this with s = '', and you are in trouble.
So, try:

     if s[-1:] != '/':
         s += '/'

To be a trifle more reliable. But, for more normal semantics,
you might prefer either:
     if s[-1:] != '/':
         s = (s or '.') + '/'
or:
     if s and s[-1] != '/':
         s += '/'

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list