0
lst = ['40', '36', '112', 'Eric', '30', 'Bob', '15', '125', '45', 'Philippe']
d = []
things = 0
summ = 0
for val in lst:
    try:
        summ+= float(val)
        things+= 1
    except ValueError:
        name = val
        d.append((name, summ, things))
        summ= 0
        things= 0


print("Name            total            # items")

for i in d:
    l = list(i)
    print(str(l[0])+ "          " + str(l[1]) + "0 $            " + str(l[2]))

How would I print the grid at the end without the weird spaces I added? Each column and row should be aligned.

metal
  • 27
  • 4

1 Answers1

2

I'd use a format-string and specify field widths and alignment to let Python automatically space things out for me, something like:

for name, value, nitems in d:
    print(f"{name:10} {value:>10.2f} $ {nitems:>16}")

giving:

Name            total            # items
Eric           188.00 $                3
Bob             30.00 $                1
Philippe       185.00 $                3

note that this uses destructing assignment to automatically seperate out the elements of the tuples stored inside d.

Sam Mason
  • 15,216
  • 1
  • 41
  • 60