Fixed length lists from .split()?

George Sakkis george.sakkis at gmail.com
Fri Feb 2 15:12:19 EST 2007


On Feb 1, 2:40 pm, Bob Greschke <b... at passcal.nmt.edu> wrote:

> This idiom is what I ended up using (a lot it turns out!):
>
> Parts = Line.split(";")
> Parts += (x-len(Parts))*[""]
>
> where x knows how long the line should be.  If the line already has
> more parts than x (i.e. [""] gets multiplied by a negative number)
> nothing seems to happen which is just fine in this program's case.
>
> Bob

Here's a more generic padding one liner:

from itertools import chain,repeat

def ipad(seq, minlen, fill=None):
    return chain(seq, repeat(fill, minlen-len(seq)))

>>> list(ipad('one;two;three;four'.split(";"), 7, ''))
['one', 'two', 'three', 'four', '', '', '']

>>> tuple(ipad(xrange(1,5), 7))
(1, 2, 3, 4, None, None, None)


George




More information about the Python-list mailing list