bug in str.startswith() and str.endswith()

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu May 26 23:27:56 EDT 2011


On Thu, 26 May 2011 23:00:32 -0400, Terry Reedy wrote:

[...] 
> To me, that says pretty clearly that start and end have to be
> 'positions', ie, ints or other index types. So I would say that the
> error message is a bug. I see so reason why one would want to use None
> rather that 0 for start or None rather than nothing for end.

def my_string_function(source, x, y, z, start, end):
    if source.startswith(x+y+z, start, end): 
        ...

I want sensible defaults for start and end. What should I set them to?

def my_string_function(source, x, y, z, start=0, end=None):
    if end is None:
        flag = source.startswith(x+y+z, start)
    else:
        flag = source.startswith(x+y+z, start, end)
    if flag:
        ...

Yuck. Perhaps a better alternative is:

def my_string_function(source, x, y, z, start=0, end=None):
    t = (start,) if end is None else (start, end)
    if source.startswith(x+y+z, *t):
        ...

but that's still pretty icky.


-- 
Steven



More information about the Python-list mailing list