错误:ValueError:无法将字符串转换为float

时间:2013-07-20 15:28:23

标签: python python-3.x

我有这个错误显示我,一直运行我的代码:

import numpy as np
import matplotlib.pyplot as plt 
import glob
import scipy


pe_day = []
day = []
f = open("PE0.txt", "r").readlines()
for each_day in f:
    (day, pe) = each_day.split()
    day = str(day)
    pe_day.append(float(pe))
    print(pe_day)
    print(day[14:16])
    plt.plot(pe_day, float(day), '-',  color = 'g')    
f.close()
plt.show()

由于我一直在使用python 3.3并且我是一名新程序员,所以我不知道应该从哪里开始。

1 个答案:

答案 0 :(得分:0)

根据评论,您在第二个字段中有非数字字符。要绕过这种类型的异常,请使用类似的代码:

    try:
        pe_day.append(float(pe))
    except Exception as e:
        print "Error occured while  trying to convert pe value: %s to float " % (pe)
        print "Errors :\n\t\t", sys.exc_info()[0], ":\t", e