Turn one line into a list.
Split a short text value into pieces you can work with.
Choose the boundary between pieces.
A line such as “tea, bread, apples” is convenient to type, but a program may need three separate items. split(",") divides the string wherever it finds a comma and returns a list.
The separator is removed from the pieces, but the spaces after it remain. That is why the example cleans each piece with strip(). The first operation finds the boundaries; the second tidies the edges.
One line → separate values
tea, bread, apples
tea bread apples
Know when the shortcut is too simple.
This works for our deliberately simple list. It is not a general way to read a CSV file. Real CSV can contain quoted commas inside a field, so splitting at every comma may break a single value into two. Python’s csv module handles those rules.
Try adding one more item to this small example. Then try an empty item between two commas and inspect what happens. An empty string is still a result you may need to deal with rather than quietly assuming every piece is a real item.
line = "tea, bread, apples"
items = [part.strip() for part in line.split(",")]
print(items)Make it yours.
- Run the example and inspect the list.
- Add milk after another comma and rerun it.
- Try two commas together and find the empty entry.
What changed when you tried it?
A little nudge
Split first, then clean each returned piece.
What to look for
The original result is ['tea', 'bread', 'apples']. Two adjacent commas produce an empty-string entry.
Take it one small step further
Print len(items) to count the pieces, including any empty ones.
Pick a separator that matches the data’s actual rules.
Read more: Python · str.split ↗
No submission needed. This one is just for you.