Il Sat, 14 Mar 2009 12:13:31 +0100, Peter Otten ha scritto: > mattia wrote: > >> Il Sat, 14 Mar 2009 10:35:59 +0100, Peter Otten ha scritto: >> >>> mattia wrote: >>> >>>> How can I convert the following string: >>>> >>>> 'AAR','ABZ','AGA','AHO','ALC','LEI','AOC', >>>> EGC','SXF','BZR','BIQ','BLL','BHX','BLQ' >>>> >>>> into this sequence: >>>> >>>> ['AAR','ABZ','AGA','AHO','ALC','LEI','AOC', >>>> EGC','SXF','BZR','BIQ','BLL','BHX','BLQ'] >>> >>>>>> s = "'AAR','ABZ','AGA','AHO','ALC','LEI','AOC'" >>>>>> csv.reader(StringIO.StringIO(s), quotechar="'").next() >>> ['AAR', 'ABZ', 'AGA', 'AHO', 'ALC', 'LEI', 'AOC'] >>> >>> or >>> >>>>>> s = "'AAR','ABZ','AGA','AHO','ALC','LEI','AOC'" list(compile(s, >>>>>> "nofile", "eval").co_consts[-1]) >>> ['AAR', 'ABZ', 'AGA', 'AHO', 'ALC', 'LEI', 'AOC'] >>> >>> Peter >> >> Ok, and what about if the string is "['AAR', 'ABZ', 'AGA', 'AHO', >> 'ALC']" I wanted to use eval(string) but it is discouraged, they say. > > If you use the csv module you can remove the [] manually > > assert s.startswith("[") > assert s.endswith("]") > s = s[1:-1] > > compile() will work without the enclosing list(...) call. > > Yet another one is > > flights = re.compile("'([A-Z]+)'").findall(s) if any(len(f) != 3 for f > in flights): > raise ValueError > > Peter
Yeah, I'll also havo he handle some simple cases, for now I just used c2 = re.compile("a(?P<from>[A-Z]{3})=\[(?P<seqto>[^\]]+)\]") from_to = dict((x.group("from"), str_to_seq(x.group("seqto"))) for x in c2.finditer(rest)) Thanks a lot (I also didn't know of the any function)! -- http://mail.python.org/mailman/listinfo/python-list