Why can't float () convert my string to float?

My program gives 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 split into a list. How can I do this work and why is this happening wrong? Here are the relevant code bits:

def Main(): srcf = open(bkp, 'r') for line in srcf: liLn = line.split(',') 

... Then the next 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 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 am using Python 2.7 on an Ubuntu Linux computer.

+7
source share
1 answer

You need to strip double quotes from the string. This will give you a legal floating point string that float () can convert.

+9
source

All Articles