How to Split a String by Comma in Python
Splits a comma-separated string into a list of trimmed items using Python's built-in split and a list comprehension.
Python code
8 linesdef split_csv(line):
return [item.strip() for item in line.split(",")]
if __name__ == "__main__":
sample = "apple, banana, cherry, date"
result = split_csv(sample)
print(result)
print(f"Number of items: {len(result)}")
Output
['apple', 'banana', 'cherry', 'date']
Number of items: 4
How it works
The split(",") method breaks the string at every comma, returning a list of substrings. The list comprehension then applies .strip() to each item, removing leading and trailing whitespace like spaces after commas. This keeps the output clean and consistent, even when the input has inconsistent spacing. Using a comprehension keeps the code concise and readable without a manual loop.
Common mistakes
- Forgetting to strip whitespace, leaving items with leading/trailing spaces
- Using `.split()` without arguments, which splits on any whitespace instead of only commas
- Handling empty strings at the start or end of the input incorrectly
Variations
- Use `line.split(',')` directly if the input has no extra whitespace
- Use `re.split(r'\s*,\s*', line)` for robust splitting with optional spaces
Real-world use cases
- Converting comma-separated user input from a form field into a clean list for validation.
- Parsing CSV-like data received from an API or file before further processing.
- Splitting configuration values like 'server1,server2' into a list of endpoints.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.