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.

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

Python code

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

stdout
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

  1. Use a list comprehension: `[item.strip() for item in raw_data.split('|') if item.strip()]`
  2. 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

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.