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

Tim Chase python.list at tim.thechases.com
Tue Apr 15 16:15:47 EDT 2008


>> def nsplit(s,p,n):
>>     n -= 1
>>     l = s.split(p, n)
>>     if len(l) < n:
>>         l.extend([''] * (n - len(l)))
>>     return l
> 
> The split() method has a maxsplit parameter that I think does the same
> thing. For example:
> 
>>>> temp = 'foo,bar,baz'
>>>> temp.split(',', 1)
> ['foo', 'bar,baz']


The OP's code *does* use the maxsplit parameter of split()

The important (and missing) aspect of the OP's code in your 
example is exercised when there are *fewer* delimited pieces than 
"n":

   >>> "a,b,c".split(',', 5)
   ['a', 'b', 'c']
   >>> nsplit("a,b,c", ',', 5)
   ['a', 'b', 'c', '', '']

A few things I noticed that might "improve" the code:

- cache len(l) though my understanding is that len() is an O(1) 
operation, so it may not make a difference

- using "delim", "maxsplit", "results" instead of "p", "n" "l" to 
make it easier to read

-setting default values to match split()

   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)


My suggestion would just be to create your own utils.py module 
that holds your commonly used tools and re-uses them

-tkc





More information about the Python-list mailing list