Python
string manipulation
data processing
split and strip
Python tips

How to split by comma and strip white spaces in Python?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Splitting comma-separated text and trimming extra spaces is a very common cleanup task in Python. The straightforward solution is usually enough, but it helps to know when plain split is correct and when you should switch to a parser such as the csv module.

Use split and strip Together

str.split(',') breaks the string at each comma, but it does not remove spaces around the resulting pieces. str.strip() removes leading and trailing whitespace from each piece.

python
1text = "apple, banana,  cherry ,date"
2parts = [item.strip() for item in text.split(",")]
3
4print(parts)

Output:

text
['apple', 'banana', 'cherry', 'date']

This is the standard answer because it is readable and works for most ad hoc data cleaning tasks.

Remove Empty Values When Needed

If the input may contain repeated commas or blank fields padded with spaces, filter them out after trimming.

python
1text = "apple, banana, ,  cherry ,, date "
2parts = [item.strip() for item in text.split(",") if item.strip()]
3
4print(parts)

Output:

text
['apple', 'banana', 'cherry', 'date']

That if item.strip() clause removes entries that become empty after whitespace is stripped. It is useful when the source format is noisy and blank items should be ignored.

Know What strip Does Not Do

strip() removes whitespace only at the beginning and end of a string. It does not remove spaces inside the value.

python
1text = "New York, Los Angeles , San Francisco"
2parts = [item.strip() for item in text.split(",")]
3
4print(parts)

Output:

text
['New York', 'Los Angeles', 'San Francisco']

That is usually exactly what you want. Internal spaces are part of the data and should remain untouched.

Use csv for Real CSV Data

Plain split(',') fails when values can contain commas inside quotes. For actual CSV input, use Python's csv module instead of writing your own parser.

python
1import csv
2
3text = 'apple,"banana, ripe",cherry'
4row = next(csv.reader([text], skipinitialspace=True))
5
6print(row)

Output:

text
['apple', 'banana, ripe', 'cherry']

This is the important boundary line:

  • use split for simple comma-separated strings
  • use csv.reader for real CSV rules such as quoted commas

Trying to solve CSV parsing with split usually creates subtle bugs as soon as the data becomes more realistic.

Package the Logic in a Helper Function

If the pattern appears often, wrap it in a small function so the intent is obvious at the call site.

python
1def split_and_strip(text, delimiter=",", drop_empty=True):
2    items = [part.strip() for part in text.split(delimiter)]
3    if drop_empty:
4        items = [part for part in items if part]
5    return items
6
7
8print(split_and_strip("a, b, , c"))
9print(split_and_strip("x | y | z", delimiter="|"))

This keeps data-cleaning code consistent across a project and makes it easy to adjust later if the input format changes.

Common Pitfalls

  • Using split(',') on real CSV content that contains quoted commas.
  • Forgetting that strip() removes only leading and trailing whitespace.
  • Filtering before trimming. A field containing only spaces should usually count as empty after stripping.
  • Overusing regular expressions for a job that built-in string methods already handle clearly.
  • Forgetting that split returns strings exactly as they appear between delimiters, including tabs and other surrounding whitespace characters.

Summary

  • The common solution is [item.strip() for item in text.split(",")].
  • Add if item.strip() when blank entries should be dropped.
  • 'strip() preserves internal spaces such as those in city names.'
  • Use the csv module when commas can appear inside quoted fields.
  • Wrap the logic in a helper function if the same cleanup appears repeatedly.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.