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?
Asked
Active
Viewed 3.0k times
18

pythonsupper
- 181
- 1
- 1
- 3
3 Answers
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
-
3I think you have it a bit backwards: `'3,2,6'.split(',')` – Donald Miner Aug 13 '10 at 14:01
-
1@orangeoctopus It works fine anyway, `int` discard surrounding whitespace – Aug 13 '10 at 14:11
-
1I know this is an old answer, but I wanted to add to it. if someone needs to validate the input before casting it to an int() (which will throw an exception if you dont) then you can just add `if x.isdigit()` right at the end – John Ruddell Nov 19 '14 at 18:28
-
@JohnRuddell added that into my answer – Wayne Werner Nov 19 '14 at 23:58
-
1FWIW, `.isdigit` is fine if you don't need to handle negative integers. – PM 2Ring Sep 13 '16 at 11:39
25
map( int, myString.split(',') )

wheaties
- 35,646
- 15
- 94
- 131
-
5@Matt: actually, while personally I love the functional style, list comprehensions are more Pythonic – Eli Bendersky Aug 13 '10 at 14:06
-
Is there any way for, s="a,b;c,d" to sList=[['a','b'],['c','d']] ? – Suat Atan PhD Apr 05 '15 at 15:57
-
9In Python 3, you'd have to wrap that in a `list` call because `map` returns an iterator not a list. Thus: `list(map(int, my_string.split(',')))` – PM 2Ring Sep 13 '16 at 11:34
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