string to list? possible?
Christophe Delord
christophe.delord at free.fr
Sun Jan 20 16:43:07 EST 2002
This could also be written as follow:
>>> x="[1, 2, 3, 4]"
>>> map(int,x[1:-1].split(','))
[1, 2, 3, 4]
>>>
Roy Smith wrote:
> 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.
>
More information about the Python-list
mailing list