Skip to content
techskilldaily.
The archiveNo. 022
A little Python

Turn one line into a list.

Split a short text value into pieces you can work with.

2 min read 5 min to try
MAKE ROOM FORoneSMALL SKILL

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

Input

tea, bread, apples

Clean pieces

tea bread apples

This example assumes commas never occur inside an item.

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.

A small example to try
line = "tea, bread, apples"
items = [part.strip() for part in line.split(",")]
print(items)
Your turn 5 minutes

Make it yours.

  1. Run the example and inspect the list.
  2. Add milk after another comma and rerun it.
  3. 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.

Keep this bit

Pick a separator that matches the data’s actual rules.

Read more: Python · str.split ↗

No submission needed. This one is just for you.

Another spark of curiosityShow only the rows you need.