[英]Wont convert decimal number in string format to float
我的代码有问题,我只是不明白为什么它不起作用。 编码:
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)
当打印到控制台时,total_product为:
5.94
807.92
2000.40
0.00
我不明白的是为什么它不将每个转换成浮点型,而是将错误打印到控制台:
TypeError:无法连接
'str'
和'float'
对象
如果有人可以告诉我如何修复或/以及为什么要这样做,我将非常乐意。
您的代码实际上已成功地将每个total_product
转换为float。 错误出现在代码段的最后一行,您尝试将字符串输出与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))
将类型为float
的total
变量转换为string
receipt.write("Total of Items: " + str(total))
这是一个例子:
total = 13.54
str(total)
>> '13.54'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.