Significance of "start" parameter to string method "endswith"

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Thu Apr 19 19:12:42 EDT 2007


On Thu, 19 Apr 2007 13:57:16 -0700, Boris Dusek wrote:

>> > what is the use-case of parameter "start" in string's "endswith"
>> > method?
> 
>> def foo(function,instance,param):
>>     if function(instance,param,2,4):
>>         return True
>>     else: return False
>>
>> The function must work whether you pass it
>> foo(str.endswith,"blaahh","ahh"), or
>> foo(str.startswith,"blaahh","aah"). This is a really bad example, but
>> it gets the point across that similar functions must have similar
>> parameters in order to be Pythonic.
> 
> Thanks for explanation, this point makes sense. And I agree that I can
> hardly imagine any use of both parameters :-).

No, sorry, it doesn't make sense because not all string methods take the
same arguments! See, for instance, ''.translate() and ''.lower().

The best reason for giving string methods and functions start and end
parameters is to avoid copying potentially large lumps of text. Here's a
silly example. Instead of doing this:

while text:
    p = text.find('parrot')
    buffer = text[:p]
    text = text[p:]
    do_something_with(buffer)

You can do this:

p = 0
while text:
    p = text.find('parrot', p)
    do_something_with(buffer, p)

which avoids copying text unnecessarily.

Now, obviously there are better ways to re-write that code (e.g. by
splitting the text into chunks with split) but it should illustrate the
concept.


-- 
Steven.




More information about the Python-list mailing list