On Fri, 20 Apr 2007 15:21:56 -0700, John Machin wrote: > On Apr 20, 9:12 am, Steven D'Aprano > <[EMAIL PROTECTED]> 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:
There are always trade-offs. > > (1) "while text"? "while 1" is a more obvious way of stress-testing > your CPU fan :-) but perhaps you meant "while p >= 0". No, I meant exactly what I said. You might notice that text becomes smaller after each iteration: text = text[p:] Eventually text becomes the empty string and the while loop is exited cleanly. "while p >= 0" would be an alternative, but you still need to copy chars into a buffer, and you still need to shrink the text or else you'll just keep getting the same p over and over again. > (2) 4s/buffer/text/ Yes, a silly typo caused by copy-and-paste-without-proof-reading. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list