Recurring patterns: Am I missing it, or can we get these added to the language?

John Krukoff jkrukoff at ltgc.com
Tue Apr 15 17:25:39 EDT 2008


On Tue, 2008-04-15 at 13:48 -0700, Jeffrey Froman wrote:
> Tim Chase wrote:
> >    def nsplit(s, delim=None, maxsplit=None):
> >      if maxsplit:
> >        results = s.split(delim, maxsplit)
> >        result_len = len(results)
> >        if result_len < maxsplit:
> >          results.extend([''] * (maxsplit - result_len)
> >        return results
> >      else:
> >        return s.split(delim)
> 
> I'll add a couple more suggestions:
> 
> 1. Delay the test for maxsplit, as str.split() does the right thing if
> maxsplit is None.
> 
> 2. Use a generator to pad the list, to avoid interim list creation. This
> works fine, because list.extend() accepts any iterable. This also shortens
> the code a bit, because xrange() does the right thing in this case with
> negative numbers. For example:
> 
> def nsplit(s, delim=None, maxsplit=None):
>     results = s.split(delim, maxsplit)
>     if maxsplit is not None:
>         results.extend('' for i in xrange(maxsplit - len(results)))
>     return results
> 
> 
> Jeffrey
> 

Neither of these quite match what the OP's nsplit function did, as his n
parameter (maxsplit here) actually specified the number of list items in
the result, not the number of splits to perform. Which makes matching
the default split parameters kind of pointless, as why bother doing all
this work to return a 0 item list in the default maxsplit = None case.
-- 
John Krukoff <jkrukoff at ltgc.com>
Land Title Guarantee Company




More information about the Python-list mailing list