converting lists to strings to lists

Steven D'Aprano steve at REMOVETHIScyber.com.au
Wed Apr 12 10:28:36 EDT 2006


On Wed, 12 Apr 2006 06:53:23 -0700, robin wrote:

> hi,
> 
> i'm doing some udp stuff and receive strings of the form '0.870000
> 0.250000 0.790000;\n'
> what i'd need though is a list of the form [0.870000 0.250000 0.790000]
> i got to the [0:-3] part to obtain a string '0.870000 0.250000
> 0.790000' but i can't find a way to convert this into a list. i tried
> eval() but this gives me the following error:
> 
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "<string>", line 1
>     .870000 0.250000 0.79000


# untested!
def str2list(s):  
    """Expects a string of the form '0.87 0.25 0.79;\n' and
    returns a list like [0.87, 0.25, 0.79]

    WARNING: this function has only limited error checking.
    """
    s = s.strip()  # ignore leading and trailing whitespace
    if s.endswith(';'): 
        s = s[:-1]
    L = s.split()
    assert len(L) == 3, "too many or too few items in list."
    return [float(f) for f in L]


> and i have the same problem the other way round. e.g. i have a list
> which i need to convert to a string in order to send it via udp.

That's even easier.

def list2str(L):
    """Expects a list like [0.87, 0.25, 0.79] and returns a string 
    of the form '0.870000 0.250000 0.790000;\n'.
    """
    return "%.6f %.6f %.6f;\n" % tuple(L)



-- 
Steven.




More information about the Python-list mailing list