Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"pythonic" method to parse a string of comma-separated integers into a list of integers?

Tags:

python

I am reading in a string of integers such as "3 ,2 ,6 " and want them in the list [3,2,6] as integers. This is easy to hack about, but what is the "pythonic" way of doing it?

like image 811
pythonsupper Avatar asked Aug 13 '10 13:08

pythonsupper


1 Answers

mylist = [int(x) for x in '3 ,2 ,6 '.split(',')]

And if you're not sure you'll only have digits (or want to discard the others):

mylist = [int(x) for x in '3 ,2 ,6 '.split(',') if x.strip().isdigit()]
like image 139
Wayne Werner Avatar answered Sep 21 '22 13:09

Wayne Werner