[英]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.