How to Parse Delimited Data into a Python List
Splits a pipe-delimited string, strips whitespace, filters empty items, and returns a clean list with a loop.
Python code
16 linesdef parse_data(raw_data):
"""Parse a pipe-delimited string into a list of cleaned items."""
items = raw_data.split("|")
parsed = []
for item in items:
cleaned = item.strip()
if cleaned:
parsed.append(cleaned)
return parsed
if __name__ == "__main__":
data = " apple | banana | cherry |"
result = parse_data(data)
print(f"Parsed: {result}")
print(f"Count: {len(result)} items")
Output
Parsed: ['apple', 'banana', 'cherry']
Count: 3 items
How it works
The split('|') call breaks the raw string into substrings at every pipe character. The for loop then iterates over those substrings. strip() removes leading and trailing whitespace from each item. The if cleaned: check skips empty strings—including the trailing empty item from the trailing pipe. Appending only non-empty, cleaned strings builds the final parsed list.
Common mistakes
- Forgetting to strip whitespace, leaving spaces in the parsed items.
- Not filtering empty strings, so trailing delimiters create blank list entries.
- Using `split()` without an argument, which splits on whitespace instead of pipes.
Variations
- Use a list comprehension: `[item.strip() for item in raw_data.split('|') if item.strip()]`
- Use `filter` with `str.strip` to drop empty entries in one pass.
Real-world use cases
- Parsing a line from a legacy CSV file that uses a custom delimiter like a pipe.
- Cleaning user-input tags separated by delimiters before storing them in a database.
- Reading a config string that lists allowed values and splitting them into a validated list.
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.