newbe how to read in a string?

Chris Gonnerman chris.gonnerman at usa.net
Fri Mar 23 08:59:07 EST 2001


----- Original Message ----- 
From: "William Famy" <william.famy at noos.fr>
Subject: newbe how to read in a string?


> Hi.
> 
> I am looking how to read in a string.
> 
> Ex
> a='2000/12/28,24.3,87.1,65.4'
> 
> I whant to extract the 87.1. In C i would code by a
> scanf("%s,%f,%f,%f\n"),...

Actually what you are asking is how to *parse* a string you have already
read.  The easy way for this particular string is:

    import string
    d,n1,n2,n3 = string.split(a, ",")
    n1 = float(n1)
    n2 = float(n2)
    n3 = float(n3)

If the list of numbers is of variable length, this might be cool:

    import string
    seq = string.split(a, ",")
    for i in range(1, len(seq)): # this skips the 0 index,
        seq[i] = float(seq)      # which needs to stay a string.

In Python 2.0 the code might be shorter, using string methods and list
comprehension, but I personally prefer the "old way" myself.






More information about the Python-list mailing list