Format Numbers in Displayed Counts (Solution)

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.

Know Your Starting Point

Currently, your word count script should look something like this:

Python 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:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.