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:
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:
Isn’t that neat? Let us try it with our address example from above:
The output is:
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?
The output is:
Note that the list has some elements which are empty strings. If you wish to remove them you can use a list comprehension:
The output is, as expected:
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.
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.