Significance of "start" parameter to string method "endswith"
John Machin
sjmachin at lexicon.net
Fri Apr 20 18:21:56 EDT 2007
On Apr 20, 9:12 am, Steven D'Aprano
<s... at REMOVE.THIS.cybersource.com.au> wrote:
> 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.
... but increases the care and attention required when coding:
(1) "while text"? "while 1" is a more obvious way of stress-testing
your CPU fan :-) but perhaps you meant "while p >= 0".
(2) 4s/buffer/text/
Cheers,
John
More information about the Python-list
mailing list