How to Parse a Comma String into a List of Integers in Python

Converts a comma-separated string into a list of integers, handling spaces and empty inputs.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 13 views 0 copies

Python code

10 lines
Python 3.9+
def parse_csv_to_ints(text: str) -> list[int]:
    """Parse a comma-separated string into a list of integers."""
    if not text.strip():
        return []
    return [int(part.strip()) for part in text.split(",") if part.strip()]

if __name__ == "__main__":
    sample = "10, 20, 30, 40, 50"
    result = parse_csv_to_ints(sample)
    print(result)

Output

stdout
[10, 20, 30, 40, 50]

How it works

The split(",") method separates the string at each comma, producing a list of substrings. A list comprehension then strips whitespace from each part with .strip() and converts it to an integer with int(). The if part.strip() condition filters out empty strings, which would otherwise cause a ValueError. For empty or whitespace-only input, the function returns an empty list upfront to avoid issues. This pattern is concise, readable, and robust for typical CSV-like data.

Common mistakes

  • Forgetting to strip whitespace, causing `int(' 10')` to fail with a ValueError.
  • Not filtering empty strings, which leads to errors when input has trailing commas.
  • Assuming input is always valid, without handling non-numeric parts gracefully.

Variations

  1. Use `map(int, text.split(','))` if the input has no spaces and no empty parts.
  2. Use a try/except block to skip or handle invalid values instead of failing.

Real-world use cases

  • Parsing configuration values like port lists from environment variables.
  • Reading user input in a CLI tool that accepts comma-separated IDs.
  • Extracting numeric tokens from log data or CSV snippets in an ETL pipeline.

Sponsored

Run this sample

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

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.