Recurring patterns: Am I missing it, or can we get these added to the language?
Jeffrey Froman
jeffrey at fro.man
Tue Apr 15 16:48:18 EDT 2008
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
More information about the Python-list
mailing list