Fixed length lists from .split()?

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Sat Jan 27 06:44:26 EST 2007


Duncan Booth:
> def nsplit(s, sep, n):
>     return (s.split(sep) + [""]*n)[:n]

Another version, longer:

from itertools import repeat

def nsplit(text, sep, n):
    """
    >>> nsplit("bcsn; 1000001; 1456", ";", 3)
    ['bcsn', ' 1000001', ' 1456']
    >>> nsplit("bcsn; 1000001", ";", 3)
    ['bcsn', ' 1000001', '']
    >>> nsplit("bcsn", ";", 3)
    ['bcsn', '', '']
    >>> nsplit("", ".", 4)
    ['', '', '', '']
    >>> nsplit("ab.ac.ad.ae", ".", 2)
    ['ab', 'ac', 'ad', 'ae']
    """
    result = text.split(sep)
    nparts = len(result)
    result.extend(repeat("", n-nparts))
    return result

if __name__ == "__main__":
    import doctest
    doctest.testmod()

Bye,
bearophile




More information about the Python-list mailing list