String to sequence

Peter Otten __peter__ at web.de
Sat Mar 14 07:13:31 EDT 2009


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



More information about the Python-list mailing list