In this lesson, you’ll learn how to improve your wordcount
command by aligning the numbers in the output. This approach will make the counts more consistent and easier to read, especially when handling larger texts.
Note: You’re about halfway through the challenge. Nice work! Since this is a new content format we’re trying out, we’d love to know what you think so far. Please share your feedback. It only takes a minute and helps us improve future challenges!
Know Your Starting Point
Currently, your word count script should look something like this:
src/wordcount.py
import sys
def main():
raw_text = sys.stdin.buffer.read()
text = raw_text.decode("utf-8")
num_lines = text.count("\n")
num_words = len(text.split())
num_bytes = len(raw_text)
print(num_lines, num_words, num_bytes)
This code successfully reads text from standard input and counts the number of lines, words, and bytes, including multi-byte characters. Your task now is to modify the output formatting so that each count is right-aligned based on the maximum width among the counts.
Align Numbers in the Output
To achieve a neatly aligned output, you can use Python’s formatted string literals, or f-strings. They allow you to specify formatting options directly within the string. You’ll use them to ensure that each count is right-aligned based on the maximum number of digits.
Here’s an example, illustrating what you’re aiming to achieve: