This tutorial will discuss about unique ways to convert comma-separated string to list of integers in Python.
Table Of Contents
Quick Solution:
First split the string using a comma as a delimeter i.e.
strValue.split(',')
It will split the string into multiple strings by using a comma as a delimeter. It returns a sequence of substrings from the string. Then convert each substring to an integer, and create a list from these converted integers using List Comprehension.
Let’s see the complete example,
strValue = "11,24, 56, 23, 67, 80" # Convert comma-separated string to List of Integers listOfInts = [int(elem) for elem in strValue.split(',') ] print(listOfInts)
Output
[11, 24, 56, 23, 67, 80]
It converted a comma-separated string to List of Integers.
Frequently Asked:
But this example will only work if list has digits, and comma characters. What if string has some non numeric characters? In that scenario, the above example will raise an error. To handle that scenarion, checkout the next example.
Better Solution
Split the string into a list of substrings using the split() function. Then select only those strings from the list which are numeric, and convert them to integers. Do, all this in a List Comprehension, and it will return a list of integers.
Let’s see the complete example,
strValue = "11,24, 56, 23, This, is, 67, a, 80" # Convert comma-separated string to List of Integers listOfInts = [int(elem) for elem in strValue.split(',') if elem.strip().isnumeric()] print(listOfInts)
Output
[11, 24, 56, 23, 67, 80]
Summary
We learned how to convert a comma-separated string to List of Integers in Python. Thanks.