Pybites Logo Rust Platform

cut: Extract a Field

Medium +3 pts

🎯 cut -d: -f1 /etc/passwd pulls the first colon-separated field (the username) from each line. In Python you'd split and index:

def cut(text: str, delim: str, field: int):  # field is 1-based
    if field == 0:
        raise ValueError("field values may not include zero")
    out = []
    for line in text.splitlines():
        parts = line.split(delim)
        if len(parts) >= field:
            out.append(parts[field - 1])
    return out


assert cut("foo:bar\nbaz:qux", ":", 1) == ["foo", "baz"]
assert cut("foo:bar\nbaz:qux", ":", 2) == ["bar", "qux"]
assert cut("foo:bar\nbaz:qux", ":", 3) == []
assert cut("foo:bar\nbaz:qux", ":", 4) == []
try:
    assert cut("foo:bar\nbaz:qux", ":", 0)
except ValueError as e:
    assert str(e) == "field values may not include zero"
else:
    raise AssertionError("Expected ValueError")

Two cases pull in different directions: a missing field (some lines are too short) is normal, those we skip.

However field == 0 is a bad request. Real cut rejects it: cut: [-bcf] list: values may not include zero. Rust lets you model that split cleanly: one path returns data, the other returns an error.

Login to see the full exercise.