Kodeclik Blog
How to convert a comma-separated string into a list in Python
You will often encounter a need to take a string which has values separated by commas and map the contents of the string into a list. Consider for instance a string like “123, Main Street, Littletown, California”. We might want to parse out individual aspects of the string like “123”, “Main Street”, “Littletown”, and “California”, to capture the door number, street, town, and state information. This is very easy to do in Python!
Consider a string like “K,o,d,e,c,l,i,k”. The easiest way to separate out the individual parts separated by commas into list elements is to use the split method:
mystring = "K,o,d,e,c,l,i,k"
print(mystring.split(','))
The split method takes an argument which is the separator used to separate the values, which in our case is a comma. The output will be:
['K', 'o', 'd', 'e', 'c', 'l', 'i', 'k']
Isn’t that neat? Let us try it with our address example from above:
myaddress = "123, Main Street, Littletown, California"
print(myaddress.split(','))
The output is:
['123', ' Main Street', ' Littletown', ' California']
as expected. Note that the spaces in the original string are carried over into individual elements and you might have to strip them as a post-processing step, depending on your needs. Also note that “123” is recognized as a string, not as an integer. Again you should use a function like int() to convert it into an integer (after recognizing it as such).
What happens if your string has two commas in succession?
example = "1,,2,,3,,4"
print(example.split(','))
The output is:
['1', '', '2', '', '3', '', '4']
Note that the list has some elements which are empty strings. If you wish to remove them you can use a list comprehension:
example = "1,,2,,3,,4"
print([x for x in example.split(',') if (x != '')])
The output is, as expected:
['1', '2', '3', '4']
To summarize, converting a comma-separated string into a list in Python is extremely easy using the the handy split() method rather than writing your own loops.
If you liked this blogpost, learn how to check for an empty string in Python.
Also learn how to do the reverse of what is covered in this blogpost, i.e., how to convert a Python list into a string interspersed with commas.
For more Python content, checkout the math.ceil() and math.floor() functions! Also
learn about the math domain error in Python and how to fix it!
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.