【发布时间】:2020-08-21 01:35:01
【问题描述】:
我有一个名为 cart.txt 的简单 .txt 文件,其中包含 4 行文本和数字,并且全部用逗号分隔,即
23453, 1, 45.64, 白色, 手套
25753, 2, 78.32, 红色, 包
23346, 1, 24.54, 蓝色, 俱乐部
87653, 4, 76.12, 绿色, 球
我需要提取价格,然后求和。到目前为止,我有:
with open("cart.txt", "r") as text_file:
for line in text_file:
part, quantity, price, desc1, desc2 = line.split(", ")[2]
total = sum([float(price) for price in line])
print("The total price for the awesome Fathers Day gifts you bought is ${}".format(total))
当我运行程序时,我收到一条错误消息,提示 python 无法将 str 转换为浮点数:','。
如果我删除零件、数量等并在包含 line.split 的那一行打印,我会收到所有 4 个价格,最后没有任何逗号。为什么 python 添加逗号,不允许我将其转换为浮点数?非常感谢任何帮助。
【问题讨论】: