Start learning free

LESSON 370 OF 410 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: cat v2 — Number Lines (-n) in Python

Practice

Now build the -n flag of the cat tool, as a new function. It prints every line preceded by its 1-based line number, right-aligned in 6 columns, then a tab character, then the line text. Blank lines are numbered too, and an empty list gives an empty string.

Function signature:

def numberedCat(self, lines: List[str]) -> str:

Format per line: the line number right-aligned in a field 6 characters wide (padded with spaces on the left), then a literal tab (\t), then the original line.

Example:

Input: lines = ["hello", "world", "foo"]

Output:
"     1\thello\n     2\tworld\n     3\tfoo"

When printed:
     1	hello
     2	world
     3	foo

Loop over the lines with their indices, build each formatted line, then join them with "\n". The tricky bit is right-aligning the number in 6 columns — Python's f-string format spec does this for you.

Use f"{i+1: >6}\t{lines[i]}" — the : >6 format right-aligns the integer in a 6-character field. Append each formatted string to a list, then return "\n".join(out).

The full solution:
class Solution:
    def numberedCat(self, lines):
        out = []
        for i in range(len(lines)):
            out.append(f"{i+1: >6}\t{lines[i]}")
        return "\n".join(out)

STEP 1 OF 4
    Ctrl + Enter to check

    Cat V2 in Python

    Keep going with PythonAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free