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.
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.
Output:
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.
Output:
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.
Output:
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.
Output:
This is the important boundary line:
- use
splitfor simple comma-separated strings - use
csv.readerfor 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.
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
splitreturns 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
csvmodule when commas can appear inside quoted fields. - Wrap the logic in a helper function if the same cleanup appears repeatedly.
Related reading
- How to split data based on a column value in sklearn
- How to split text without spaces into list of words
- How to state in requirements.txt a direct github source
- How to step through Python code to help debug issues?
- How to stop a looping thread in Python?
- How to stop Python Kafka Consumer in program?
- how to store numpy arrays as tfrecord?
- How to stratify the training and testing data in Scikit-Learn?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.