"10, 20, 30" to [10, 20, 30]
Tim Williams
tim at tdw.net
Thu Nov 23 06:35:28 EST 2006
On 23/11/06, Steven D'Aprano <steve at remove.this.cybersource.com.au> wrote:
> On Thu, 23 Nov 2006 03:13:10 -0800, Daniel Austria 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
>
>
> It is a dangerous solution if your data is coming from an untrusted source.
>
> >>> s = "10, 20, 30"
> >>> L = [x.strip() for x in s.split(',')]
> >>> L
> ['10', '20', '30']
> >>> L = [int(x) for x in L]
> >>> L
> [10, 20, 30]
>
> Or, as a one liner: [int(x.strip()) for x in s.split(',')]
You don't need the strip()
>>> int(' 10 ')
10
>>>
:)
More information about the Python-list
mailing list