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

Fredrik Lundh fredrik at pythonware.com
Thu Nov 23 09:17:45 EST 2006


Tim Williams wrote:

>> 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
>>>>

and the use of a list comprehension is pretty silly to, given that you want
to apply the same *function* to all items, and don't really need to look
it up for every item:

    map(int,  s.split(','))

</F> 






More information about the Python-list mailing list