Fixed length lists from .split()?

Duncan Booth duncan.booth at invalid.invalid
Fri Jan 26 13:13:56 EST 2007


Bob Greschke <bob at passcal.nmt.edu> wrote:

> Is there a fancy way to get Parts=Line.split(";") to make Parts always 
> have three items in it, or do I just have to check the length of Parts 
> and loop to add the required missing items (this one would just take 
> Parts+=[""], but there are other types of lines in the file that have 
> about 10 "fields" that also have this problem)?

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

>>> nsplit("bcsn; 1000001; 1456", ";", 3)
['bcsn', ' 1000001', ' 1456']
>>> nsplit("bcsn; 1000001", ";", 3)
['bcsn', ' 1000001', '']
>>> 



More information about the Python-list mailing list