printing formatted list items on the same line in python

Solution 1:

when you print a character to the terminal the cursor position moves forward. When you print a newline the cursor goes one position down. You'd have to manually bring it up again to print in the above line. You could use ANSI Escape Codes to control the position of the cursor. It's a lot more hard and complex.

You achieve the desired output by changing how to represent the equation. Store each of the equations as [operand1, sign, operand2]. Now, simply print all operand1 in a single line. print sign and operand 2 next. Then print -----.

def fmt(lst):
    op1, sign, op2 = zip(*map(str.split, lst))
    line1  = "\t".join([f"{op:>5}" for op in op1])
    line2  = "\t".join([f"{s:<1}{op:>4}" for s, op in zip(sign, op2)])
    line3  = "-----\t"*len(lst)
    print("\n".join([line1, line2, line3])

fmt(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"])

Output:

   32    3801      45     123
+ 698   -   2   +  43   +  49
-----   -----   -----   -----