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?
views:
99answers:
3I think you have it a bit backwards: `'3,2,6'.split(',')`
orangeoctopus
2010-08-13 14:01:07
@orangeoctopus It works fine anyway, `int` discard surrounding whitespace
delnan
2010-08-13 14:11:09
@orangeoctupus - Yeah, I edited it when I realized that. But apparently I'm quick like a fox so it doesn't show I've edited it (at least to me...) ;)
Wayne Werner
2010-08-13 14:40:37
@Wayne, now people like delnan think I'm an idiot :(
orangeoctopus
2010-08-13 17:55:27
@orangeoctopus, sorry, I'll be slower than a fox next time... :)
Wayne Werner
2010-08-13 18:02:06
+1
A:
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.
Eli Bendersky
2010-08-13 13:59:24
@Anurag: Who said they had to be integers? The OP only provided sample data...
katrielalex
2010-08-13 14:29:51
@Anurag: "teach him to fish..." - ever heard that fable? It's what I'm trying to do here. Just parsing a string of commas is rarely *the* task one attempts to solve, behind this there are more complex requirements. If I'm wrong, no harm done, other answers provide the simpler approach
Eli Bendersky
2010-08-13 16:57:03
@katrielalex, the OP said, "I'm reading in a string of integers...". For a robust solution it's better to use the csv module as Eli recommends, of course.
Wayne Werner
2010-08-13 18:07:50
@Eli, i have heard that fable, but sometimes for a very specific problems, we need not use complex solutions, like using csv module to read a list of integers
Anurag Uniyal
2010-08-14 05:35:58
@Matt: actually, while personally I love the functional style, list comprehensions are more Pythonic
Eli Bendersky
2010-08-13 14:06:55