Why does float() fail to convert my string to a float?
My program is giving me an error when it tries to convert a string from a list of strings to a floating point number. The list is read from a line in a CSV text file and then separated into a list. How do I make this work and why is it going wrong? Here are the relevant bits of code:
def Main():
srcf = open(bkp, 'r')
for line in srcf:
liLn = line.split(',')
...Then the following function is called...
def Pred_PSME(liLn):
dbh = float(liLn[6])
Here is the line from the file:
1345327,20486,"ABCO","Abies concolor","Y","Y","31.496","0.0779","19.3567",,"0.5602","0",1,"0.9268","11.8968","2.6832","6.6646","2399.256",54.47,24.15,248.47,42.19,9.16,8.16,9.23,272.27,264.11,369.30,345.15,71.80,0.00,0.00,4393.57,4106.22,3239.25,3142.07,854.30,0.00,0.00,,12.70,10.16,15.24,0.02,0.04,0.38,0.38,0.00,0.00,1.95,1.83,1.44,1.40
I get this error message:
Traceback (most recent call开发者_如何学Go last):
File "/home/cfws/python/error_calcs/FC_NF_PredInt_Gen8.py", line 263, in <module>
Main()
File "/home/cfws/python/error_calcs/FC_NF_PredInt_Gen8.py", line 36, in Main
li_tBQI = BQI_Calc(liLn)
File "/home/cfws/python/error_calcs/FC_NF_PredInt_Gen8.py", line 63, in BQI_Calc
di_eqns = {"PSME": Pred_PSME(liLn), "ABAM":Pred_ABAM(liLn), \
File "/home/cfws/python/error_calcs/FC_NF_PredInt_Gen8.py", line 172, in Pred_PSME
dbh = float(liLn[6])
ValueError: could not convert string to float: "31.496"
I'm using Python 2.7 on an Ubuntu Linux computer.
You need to strip the double quotes off the string. This will then you give a legitimate floating point string that float() can convert.
精彩评论