"10, 20, 30" to [10, 20, 30]

Tim Williams tim at tdw.net
Thu Nov 23 06:24:59 EST 2006


On 23 Nov 2006 03:13:10 -0800, Daniel Austria <futurebase at gmx.at> wrote:
> Sorry,
>
> how can i convert a string like "10, 20, 30" to a list [10, 20, 30]
>
> what i can do is:
>
> s = "10, 20, 30"
> tmp = '[' + s + ']'
> l = eval(tmp)
>
> but in my opinion this is not a nice solution
>

Not nice, especially if you can't control what is in s :)

A simple solution if you know s will always contain string
representations of integers is:

>>> s = "10, 20, 30"
>>> [int(x) for x in s.split(',')]
[10, 20, 30]
>>>

Otherwise a good starting point might be:

>>> for i in s.split(','):

HTH :)



More information about the Python-list mailing list