Home > Blockchain >  type "decimal" included in output
type "decimal" included in output

Time:10-02

When I run this code, I get results like:

(3205, Decimal('1.000'))(28802, Decimal('7.000'))(3106, Decimal('1.000'))(3173, Decimal('5.000')). 

I don't want to see the "decimal" word included in the output, how do I avoid this?

cur.execute('SELECT tk_product_ord, SUM(tk_qty_ord) as qty_required '
        'FROM table1 WHERE tk_date = 15047 AND tk_prod_group = 11 '
        'GROUP BY tk_product_ord;')

answer = cur.fetchall()

file = open("test_data_output.txt")
with open("test_data_output.txt", "w") as line:
    for item in answer:
        line.write("%s\n" % str(item))
    file.close()

CodePudding user response:

The issue is you're using str(item), which will include the Decimal type name in the repr call to those objects.

By converting the decimal to a float you will remove this:

Instead of line.write("%s\n" % str(item)) you can do something like line.write(f"{item[0]}, {float(item[1])}")

CodePudding user response:

In for item in answer:, item is a tuple. In Python, if the call str on a tuple, or another collection like a list or dict, the items in the collections are shown as their repr rather than their str.

To get the output that you want, call str on each element of item and call str.join on the result:

with open("test_data_output.txt", "w") as line:
    for item in answer:
        output = ' '.join([str(elem) for elem in item])
        line.write("%s\n" % output)

The expression [str(elem) for elem in item] is a list comprehension, a way of generating a list from an existing sequence object like a list or tuple.

  • Related