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.
Python code
10 linesdef 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
[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
- Use `map(int, text.split(','))` if the input has no spaces and no empty parts.
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.