[Python-Dev] Proof of the pudding: str.partition()

tony@lownds.com tony at lownds.com
Wed Aug 31 03:09:39 CEST 2005


I once wrote a similar method called cleave(). My use case involved a
string-like class (Substr)  whose instances could report their position in
the original string. The re module wasn't preserving
my class so I had to provide a different API.

  def cleave(self, pattern, start=0):
    """return Substr until match, match, Substr after match

    If there is no match, return Substr, None, ''
    """

Here are some observations/questions on Raymond's partition() idea. First
of all, partition() is a  much better name than cleave()!

Substr didn't copy as partition() will have to, won't many of uses of
partition() end up being
O(N^2)?

One way that gives the programmer a way avoid the copying would be to
provide a string method
findspan(). findspan() would returns the start and end of the found
position in the string. start >
end could signal no match; and since 0-character strings are disallowed in
partition, end == 0
could also signal no match. partition() could be defined in terms of
findspan():

start, end = s.findspan(sep)
before, sep, after = s[:start], s[start:end], s[end:]

Just a quick thought,

-Tony



More information about the Python-Dev mailing list