不转换字符串形式的十进制数

2024-06-08 15:34:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个问题,我的代码,我只是不明白为什么它不工作。代码:

total = 0
with open("receipt.txt", "r") as receipt:
    for line in receipt:
        the_line = line.split(",")
        total_product = the_line[4]
        total_product = total_product.translate(None, '\n')
        print total_product
        total += float(total_product)

with open("receipt.txt", "a") as receipt:
    receipt.write("Total of Items:            " + total)

当打印到控制台时,总的产品是:

5.94
807.92
2000.40
0.00

我不明白的是为什么它不把每一个都转换成浮点数,而是把错误打印到控制台上:

TypeError: cannot concatenate 'str' and 'float' objects

如果有人能告诉我怎么修或/和为什么要修,我会很高兴的。你知道吗


Tags: the代码intxtforaswithline
2条回答

将类型为floattotal变量转换为string

receipt.write("Total of Items:            " + str(total))

举个例子:

total = 13.54
str(total)
>> '13.54'

实际上,您的代码正在成功地将每个total_product转换为浮点。错误出现在代码段的最后一行,您试图将字符串输出与total变量(仍然是一个浮点)的值连接起来。您应该使用字符串格式(推荐的解决方案):

with open("receipt.txt", "a") as receipt:
    receipt.write("Total of Items:            {:.2f}".format(total))

或者把你的浮点数转换成一个字符串:

with open("receipt.txt", "a") as receipt:
    receipt.write("Total of Items:            " + str(total))

相关问题 更多 >