18

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?

pythonsupper
  • 181
  • 1
  • 1
  • 3

3 Answers3

31
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()]
Wayne Werner
  • 49,299
  • 29
  • 200
  • 290
25
map( int, myString.split(',') )
wheaties
  • 35,646
  • 15
  • 94
  • 131
9

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
  • 263,248
  • 89
  • 350
  • 412
  • @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 Aug 13 '10 at 16:57
  • 2
    @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 Aug 13 '10 at 18:07
  • 2
    @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 Aug 14 '10 at 05:35