Pybites Logo Rust Platform

cat -n: Number the Lines

Easy +2 pts

🎯 cat -n prints each line prefixed with its line number. In Python, enumerate with a start of 1 makes this easy and concise:

def cat_n(text):
    lines = text.splitlines()
    return "\n".join(f"{i}\t{line}" for i, line in enumerate(lines, start=1))

Rust has the same enumerate and like Python's enumerate, it pairs each item with its position, but you cannot override the starting int:

for (i, c) in ['a', 'b', 'c'].iter().enumerate() {
    println!("{}: {}", i + 1, c);
    // 1: a
    // 2: b
    // 3: c
}

format! and join for text building

format! is Rust's f-string: it returns a new String from a template. \t is a tab, {} a placeholder. To assemble the final …

Login to see the full exercise.