string to list? possible?
Roy Smith
roy at panix.com
Sun Jan 20 16:32:44 EST 2002
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