convert string containing list to list (or tuple) type

Poppy znfmail-pythonlang at yahoo.com
Fri May 30 10:17:39 EDT 2008


Arrgh. One of those days where I find an answer just after posting. I spend 
hours on the code below only to find I don't know how to use split to it's 
fullest.

>>> b.strip(",").split(",")
['I', 'G', 'AQ', 'ET', 'K', 'BF']

"Poppy" <znfmail-pythonlang at yahoo.com> wrote in message 
news:g1p15p$4jo$1 at aioe.org...
> I'm reading from a database a column that has a list of codes (comma 
> seperated). When I read in the list I have a single value, see code sample 
> below values for a, b, and c. These represent possible values in my 
> database. I need to loop through each value so I can expand my data from 
> this compressed view.
>
> My code below works and creates my desired output but I believe there must 
> be a better way this is very messy. My messy function that I'd like to 
> replace is lst_codes(codes). Any alternative suggestions?
>
> this is what I begin with
> a = ',P,'
> b = ',I,G,AQ,ET,K,BF,'
> c = ',DZ,'
> this is what I want (lists or tuples are fine)
> ['P']
> ['I', 'G', 'AQ', 'ET', 'K', 'BF']
> ['DZ']
>
>
> def lst_codes(codes):
>    """ turn a string of comma seperated codes into a real list object """
>    i = 0
>    lstD = []
>    while i < len(codes):
>        a = codes[i]
>        b = ","
>        if (i + 1) < len(codes):
>            b = codes[i + 1]
>            i = i + 1
>        else:
>            b = ","
>
>        if b <> ",":
>            lstD.append(a + b)
>            i = i + 2
>        else:
>            lstD.append(a)
>            i = i + 1
>    return lstD
>
>
> a = ',P,'
> b = ',I,G,AQ,ET,K,BF,'
> c = ',DZ,'
>
> for ea in (a,b,c):
>    print lst_codes(ea.strip(","))
>
> 





More information about the Python-list mailing list