我有一个问题,我的代码,我只是不明白为什么它不工作。代码:
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
如果有人能告诉我怎么修或/和为什么要修,我会很高兴的。你知道吗
将类型为
float
的total
变量转换为string
举个例子:
实际上,您的代码正在成功地将每个
total_product
转换为浮点。错误出现在代码段的最后一行,您试图将字符串输出与total
变量(仍然是一个浮点)的值连接起来。您应该使用字符串格式(推荐的解决方案):或者把你的浮点数转换成一个字符串:
相关问题 更多 >
编程相关推荐