String-alignment formatter
str.rjust(width) pads a string with spaces on the left until it's width
characters long - the same trick you'd use to line up numbers in a column
by hand, except Python does the padding for you. Get the width right and
operands of different lengths still line up on their last digit.
That's exactly what a hand-written arithmetic problem looks like on paper:
the operand, then the operator and the other operand right below it, then a
line under both:
32
+ 698
-----
The width of that block is the longer operand's length plus 2 (one character
for the operator, one for the space after it). The top line is just the
first operand right-justified to that width. The second line is the operator
followed by the second operand, right-justified to width - 1 (leaving room
for the operator itself). The dashes are exactly width long.
Your task: write format_problems(problems), where problems is a list
of (a, op, b) tuples (op is "+" or "-"). For each tuple, build a
3-line block like the one above. Join multiple blocks with a blank line
between them, and return it all as one string.
You'll practice:
Right-justifying strings to a computed width with .rjust()
Building a multi-line result by joining pieces with \n
Show a hint
Show solution
Previous Next