"pythonic" method to parse a string of comma-separated integers into a list of integers?
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?
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()]
map( int, myString.split(',') )
While a custom solution will teach you about Python, for production code using the csv
module is the best idea. Comma-separated data can become more complex than initially appears.