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.

Easy Python 3.9+ Aug 9, 2026 Strings & text 12 views 0 copies

Python code

8 lines
Python 3.9+
def 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

stdout
['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

  1. Use `line.split(',')` directly if the input has no extra whitespace
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.