Fixed length lists from .split()?
Steven Bethard
steven.bethard at gmail.com
Tue Jan 30 09:13:15 EST 2007
On Jan 26, 11:07 am, Bob Greschke <b... at passcal.nmt.edu> wrote:
> I'm reading a file that has lines like
>
> bcsn; 1000000; 1223
> bcsn; 1000001; 1456
> bcsn; 1000003
> bcsn; 1000010; 4567
>
> The problem is the line with only the one semi-colon.
> Is there a fancy way to get Parts=Line.split(";") to make Parts always
> have three items in it
In Python 2.5 you can use the .partition() method which always returns
a three item tuple:
>>> text = '''\
... bcsn; 1000000; 1223
... bcsn; 1000001; 1456
... bcsn; 1000003
... bcsn; 1000010; 4567
... '''
>>> for line in text.splitlines():
... bcsn, _, rest = line.partition(';')
... num1, _, num2 = rest.partition(';')
... print (bcsn, num1, num2)
...
(' bcsn', ' 1000000', ' 1223')
(' bcsn', ' 1000001', ' 1456')
(' bcsn', ' 1000003', '')
(' bcsn', ' 1000010', ' 4567')
>>> help(str.partition)
Help on method_descriptor:
partition(...)
S.partition(sep) -> (head, sep, tail)
Searches for the separator sep in S, and returns the part before
it,
the separator itself, and the part after it. If the separator is
not
found, returns S and two empty strings.
STeVe
More information about the Python-list
mailing list