[Python-ideas] min_fields argument to str.split()

Guido van Rossum guido at python.org
Wed Jan 21 03:51:37 CET 2009


On Tue, Jan 20, 2009 at 5:32 PM, Calvin Spealman <ironfroggy at gmail.com> wrote:
> This might be a silly idea, but I was wondering about forcing split()
> to return at least X number of items. For example, I might be getting
> a comma separated string and i want to split it up into names, but I
> might have less than all of them. If it is just 0, 1, or 2, I can use
> partition(), but any more and that doesn't work. Besides, I don't care
> if the separator is there, just to get the values. Might also make
> sense to give the values to give by default.
>
> Example of implementing this:
>
> def split(self, sep=None, max_splits=None, min_items=None):
>    parts = self.split(sep, max_splits)
>    if len(parts) < min_items:
>        parts.extend([None] * (min_items - len(parts)))
>    return parts
>
> Use would be like this:
>
> a, b, c, d = "1,2,3".split(',', None, 4)
>
> Probably not a great idea, but I'm tossing it out there, anyway.

Doesn't strike me as easy to use; the None values returned would most
likely cause a traceback a few lines down. Returning '' might be
better, but I still think it's very marginal functionality and makes
the API ugly due to the large number of optional arguments.

-- 
--Guido van Rossum (home page: http://www.python.org/~guido/)



More information about the Python-ideas mailing list