2016-02-17 32 views
2

我的代码有问题,我只是不明白为什么它不工作。代码:当打印到控制台不会将字符串格式的十进制数字转换为浮点数

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: cannot concatenate 'str' and 'float' objects

如果有人能告诉我如何解决这个问题,或者为什么要这样做,我会喜欢它。

+0

请包含完整的错误消息和receipt.txt文件的内容。 – timgeb

+0

无关:'print >> output_file,“Total Items:”,sum(float(line.split(',')[4])for line in file)' – jfs

回答

4

您的代码实际上已成功将每个total_product s转换为浮点型。错误发生在代码片段的最后一行,您尝试将您的字符串输出与您的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)) 
+0

它现在可行,谢谢! –

2

转换的total变量,它的类型floatstring

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

下面是一个例子:

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

是的,它工作正常,谢谢。 –

相关问题