440,171 Members | 776 Online Need help? Post your question and get tips & solutions from a community of 440,171 IT Pros & Developers. It's quick & easy.

# convert string containing list to list (or tuple) type

 P: n/a 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(",")) Jun 27 '08 #1 