Number formatting not working with tabulate after printing text

Question:

I’m writing this little program learning Python and I have faced a problem. I use tabulate with number formatting set to 5 numbers after separator, to make everything look nice, and it works, until I print text in the table. After text is printed (stating that you cannot divide by 0), formatting on that column seems to be gone.

The code is:

if skaiciuoti == True:
while bp <= bg:
    if (bp-a != 0):
        y = float(a / (bp - a))
        sk1.append(a)
        sk2.append(bp)
        sk3.append(y)
        bp = bp + bz
    elif (bp - a == 0):
        sk1.append(a)
        sk2.append(bp)
        sk3.append('Veiksmas negalimas (dalyba is 0)')
        bp = bp + bz

lentele = ['A reiksme', 'B reiksme', 'Y reiksme']
duomenys = zip(sk1, sk2, sk3)

print(tabulate (duomenys, headers=lentele, floatfmt=".5f", tablefmt="grid"))

Here are pictures to better illustrate my problem:

Working one

Broken one

I have tried formatting the number before appending it to the list, but it didn’t work.

Any suggestions and ideas are welcome.

Asked By: morphix

||

Answers:

Okay, I’ve managed to fix it myself. It was really not that hard, I just didn’t think about it.

The solution that worked for me was to format number when appending it to the list (not before the list) like so

sk3.append(format(y, '.5f'))
Answered By: morphix

floatfmt must be a list or a tuple, specifying one format for each column.

In your case, use e.g.:

floatfmts = ('.5f', '.5f', '.5f')
print(tabulate (duomenys, headers=lentele, floatfmt=floatfmts, tablefmt="grid"))

(See e.g. https://bitbucket.org/astanin/python-tabulate/issues/96/floatfmt-option-is-ignored-in-python3)

Answered By: Carl
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.