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:
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.
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.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

Copyright @ Kodeclik 2024. All rights reserved.