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

Arnaud Delobelle arnodel at googlemail.com
Wed Jan 21 14:32:56 CET 2009


2009/1/21 Tal Einat <taleinat at gmail.com>:
> Calvin Spealman 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.
>
> This is not a common thing to do, and it is easy enough to implement
> in a single assignment even without a helper function:
>
> a, b, c, d = ("1,2,3".split(',', 4) + [None] * 4)[:4]
>
> This also has the advantage of giving you explicit control of the
> filler value for missing pieces.

How about this?

>>> from itertools import *
>>> def fixlen(iterable, len, item=None):
...     return islice(chain(iterable, repeat(item)), len)
...
>>> list(fixlen([1, 2, 3], 5))
[1, 2, 3, None, None]

-- 
Arnaud



More information about the Python-ideas mailing list