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
- Create an empty list named
out. The rows are produced one at a time, so they need a list to collect them. - Write a
forloop whereitakes each value ofrange(len(lines)). The index is needed twice: for the number and to pick the line. - Append this line's row to
out. An f-string builds it: the valuei + 1, aligned with the format spec: >6, then\t, thenlines[i]. - 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', whilef"{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
\tinside 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}evaluatesi + 1first and then formats it;{lines[i]}inserts the text as it is. - The input list is not changed.
outis a new list.
Edge cases and common mistakes
- Starting at 0. Using
iinstead ofi + 1numbers 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,
outstays empty, and"\n".join([])is''. - A trailing newline. Joining adds separators only between rows. Adding
\nto 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 isi + 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.
