string to list? possible?
Ewald
ehoute at zeelandnet_dot_nl
Sun Jan 20 17:34:41 EST 2002
Roy Smith <roy at panix.com> wrote in news:roy-3465F1.16324420012002
@news1.panix.com:
> aahz at panix.com (Aahz Maruch) wrote:
>
>> >i need to convert a string like "[1, 2, 3, 4]" to a list [1, 2, 3, 4].
>> >possible?
>>
>> >>> eval("[1, 2, 3, 4]")
>> [1, 2, 3, 4]
>>
>> The problem is that there's no error checking, and if you're accepting
>> input from a possibly-hostile source, it could muck with your program or
>> data files.
>
> You can solve both of those problems with:
>
> l = []
> for s in x[1:-1].split(','):
> l.append (int (s))
>
> It's a bit ugly, but does the job.
Or less ugly:
a = '[1,2,3,4]'
map(int,filter(lambda x:x.isdigit(),a))
HTH,
Ewald
More information about the Python-list
mailing list