使用csv.dictreader将字符串浮动函数错误

时间:2014-09-16 18:52:00

标签: python csv

我正在使用以下2行csv文件作为初始测试..

milk_price_per_cup,cream_price_per_cup,sugar_price_per_cup,vanilla_extract_price_per_cup,

0.70,1.65,1.0,30,

然后尝试运行以下代码:

import csv

input_file = csv.DictReader(open("ingredient_prices.csv"))

milk_price = None
cream_price = None
sugar_price = None
vanilla_price = None


for row in input_file:
    milk_price = float(row["milk_price_per_cup"])
    cream_price = row["cream_price_per_cup"]
    sugar_price = row["sugar_price_per_cup"]
    vanilla_price = row["vanilla_extract_price_per_cup"]  


    print "The milk price is %d, the cream price is %s, the sugar price is %s, and the vanilla price is %s." % (milk_price, cream_price, sugar_price, vanilla_price)

不幸的是,牛奶价格的输出并不是一个浮动......它只是0而不是0.7 ....这里发生了什么?使用Python 2.7.6

1 个答案:

答案 0 :(得分:3)

字符串格式中的

%d用于整数十进制。如果你想漂浮,你应该使用%f

详细了解string formatting options here