August 22, 2018
Convert comma separated string to integer list in Python
Problem
Given a string of comma separated numbers, we want to convert that string to a Python list of integers
Solution
The idea here is to split the string into tokens then convert each token to an integer. We can do that in a couple of ways. Let us see how…
- Use a list comprehension and the split function using the comma as a delimiter
1 2 3 |
string = " 33 , 2 , 6 " integers = [int(i) for i in string.split(',')] print(integers) |
- Same as before but using map…
1 2 3 |
string = " 33 , 2 , 6 " integers = [i for i in map(int, string.split(','))] print(integers) |
- Similar approach but using regular expressions
1 2 3 4 |
import re string = " 33 , 2 , 6 " integers = [int(i) for i in re.findall(r'\d+', string)] print(integers) |
- Finally, a manual solution
1 2 3 4 5 6 7 8 9 10 |
integers = [] c = '' for i in string: if i.isdigit(): c = c + i else: if c.isdigit(): integers.append(int(c)) c = '' print(integers) |
Thanks for visiting. Please use the comment section for questions.