Start learning free

LESSON 2 OF 69 · PROJECTS: COMMAND-LINE TOOLS

cat v2 in Python: Numbering Lines with an f-string

Practice Read the full explanation

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

    PYTHON · PROJECTS: COMMAND-LINE TOOLS

    Cat V2 in Python, explained

    Problem overview

    The first version of this cat project joined lines with newlines. This version adds the -n flag as a new method, numberedCat(self, lines). Every line gets its 1-based line number in front of it. The number is right-aligned in a field 6 characters wide, padded with spaces on the left. After the number comes a tab character (\t) and then the line's text. Blank lines are numbered too, and an empty list gives an empty string.

    For ["hello", "world", "foo"] the result is ' 1\thello\n 2\tworld\n 3\tfoo', which prints as:

         1	hello
         2	world
         3	foo
    

    Approach: format each row, then join

    The job splits into two parts. First, turn each line into a finished row: number, tab, text. Second, join the rows with "\n", as in version 1, so no newline follows the last row.

    The numbering needs the position of each line, so the loop runs over indexes, range(len(lines)). Indexes start at 0 and line numbers start at 1, so the number printed is i + 1.

    Step by step

    1. Create an empty list named out. The rows are produced one at a time, so they need a list to collect them.
    2. Write a for loop where i takes each value of range(len(lines)). The index is needed twice: for the number and to pick the line.
    3. Append this line's row to out. An f-string builds it: the value i + 1, aligned with the format spec : >6, then \t, then lines[i].
    4. Return the rows joined with "\n", after the loop. The return line is not indented, so it runs once, when every row exists.

    The solution in Python

    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)
    

    Reading the format spec : >6 from right to left: 6 is the minimum width, > means right-align, and the space before it is the fill character used for padding. Since a space is also the default fill for numbers, f"{i+1:>6}" gives the same text. A few more things to know:

    • The width is a minimum. f"{5: >6}" is ' 5', while f"{12345678:>6}" is '12345678': a longer number is never cut. With a million lines, the row for line 1000000 is '1000000\tx', one column wider than the field.
    • The \t inside the f-string is a real tab. The number and the tab are always separate characters, so a reader can split each row at the tab.
    • Braces hold expressions. {i+1: >6} evaluates i + 1 first and then formats it; {lines[i]} inserts the text as it is.
    • The input list is not changed. out is a new list.

    Edge cases and common mistakes

    • Starting at 0. Using i instead of i + 1 numbers the first line 0. The lesson numbers from 1.
    • Blank lines. They get a number too. numberedCat(["a", "", "c"]) returns ' 1\ta\n 2\t\n 3\tc': the second row is the number and the tab, with nothing after them.
    • An empty list. The loop never runs, out stays empty, and "\n".join([]) is ''.
    • A trailing newline. Joining adds separators only between rows. Adding \n to each row's f-string would put one after the last row as well.
    • Spaces instead of a tab. The separator after the number is \t, a single tab character, not several spaces. The row looks similar when printed, but the strings differ.
    • Left-aligned numbers. f"{i+1:<6}" pads on the right. The lesson wants the padding on the left, which is >.
    • Mixing up the index and the line number. The line text is lines[i], while the printed number is i + 1.

    Testing

    • ["hello", "world", "foo"] gives ' 1\thello\n 2\tworld\n 3\tfoo'.
    • ["a", "", "c"] gives ' 1\ta\n 2\t\n 3\tc'.
    • [] gives ''.

    Printing the first result shows the three numbered rows lined up under each other, with the numbers ending in the same column.

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