Parse a fixed-width mainframe extract

Python data engineering interview problem. Difficulty: intermediate. Pattern: Strings. About 15 minutes. Part of the Pro drill bank.

A nightly mainframe extract is fixed-width, not CSV. Each field lives in character positions defined by a spec. You must slice, not split on commas.

Old mainframe systems export lines where every field sits at a fixed position, with no separators. A spec tells you where each field starts and how long it is. For each line, cut out each field using its (name, start, length), remove the spaces around the text and build a dictionary of field name to text. Return a list of these dictionaries, one for each line. Write parse_fixed_width(lines, spec). With the line 'SKU1widget' and the spec sku at 0 for 4 characters and name at 4 for 6, the result is [{'sku': 'SKU1', 'name': 'widget'}]. The starter file already has the function name and its print lines. Keep them and fill in the body.

Requirements

  • Use start and length to slice each field.
  • Strip spaces around every field.
  • Return one dictionary per line.
  • Keep the line order.

Constraints

  • spec is a list of (name, start, length) tuples.
  • Lines can have padding spaces.

Examples

Input: parse_fixed_width(['SKU1widget'], [('sku', 0, 4), ('name', 4, 6)]) Output: [{'sku': 'SKU1', 'name': 'widget'}] This input follows the stated rules and produces this output.

Topics: lakebench, python, file/data-processing.

More Python interview questions · All interview problems · Learn data engineering

intermediate

Parse a fixed-width mainframe extract

Interview-style drill: Parse a list of fixed-width text lines into structured records using column offsets.

Parse fixed-width lines using the provided field spec.