[Tutor] parsing a blank-separated string into a list

Simon Brunning SBrunning@trisystems.co.uk
Wed, 6 Jun 2001 11:51:22 +0100


> From:	Eugene Leitl [SMTP:Eugene.Leitl@lrz.uni-muenchen.de]
> Assuming, I have a string like this (produced by the JME applet,
> encoding a molecule I entered):
> 
> 10 11 C 9.13 -8.85 C 10.34 -8.15 C 7.92 -8.15 C 10.34 -6.75 C 7.92 -6.75 C
> 8.43 -3.89 C 9.83 -3.89 C 8.00 -5.23 C 10.26 -5.23 C+ 9.13 -6.05 1 2 2 1 3
> 1 2 4 1 3 5 2 4 10 2 5 10 1 6 7 1 6 8 1 7 9 1 8 10 1 9 10 1
> 
> And want to turn it into a list like this:
> 
> [10, 11, C, 9.13 ... ]
> 
> How do I do it?
> 
> jmelist = map(None, jmevalue) produces
> 
> [1, 0, 1, 1, C, ...], whereas I want the blank-separted atoms.
 
Try this

mystring = '''10 11 C 9.13 -8.85 C 10.34 -8.15 C 7.92 -8.15 C 10.34 -6.75 C
7.92 -6.75 C 8.43 -3.89 C 9.83 -3.89 C 8.00 -5.23 C 10.26 -5.23 C+ 9.13
-6.05 1 2 2 1 3 1 2 4 1 3 5 2 4 10 2 5 10 1 6 7 1 6 8 1 7 9 1 8 10 1 9 10
1'''
mylist = mystring.split()

At this point, mylist consists of a list of strings. It looks like you want
the numeric strings converted into numbers. Floats by the look of it. Now,
if your strings were *all* numeric, you could do:

mylist = [float(value) for value in mylist]

and you would be fine. List comprehensions are nice. ;-)

But in your case, this would blow up with a ValueError when trying to
convert the alphabetic characters, so we'll have to do this the old
fashioned way:

for index in range(len(mylist)):
    try:
        mylist[index] = float(mylist[index])
    except ValueError:
        pass

BTW, if you are not familiar with floats, you have a lot of surprises coming
up. If you are, then you *still* have a lot of surprises coming up. ;-)

HTH,
Simon B.




-----------------------------------------------------------------------
The information in this email is confidential and may be legally privileged.
It is intended solely for the addressee. Access to this email by anyone else
is unauthorised. If you are not the intended recipient, any disclosure,
copying, distribution, or any action taken or omitted to be taken in
reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot
accept liability for statements made which are clearly the senders own.