为什么float()无法将我的字符串转换为浮点数?

时间:2011-03-10 03:10:07

标签: python

我的程序在尝试将字符串列表中的字符串转换为浮点数时给出了错误。该列表从CSV文本文件中的一行读取,然后分成一个列表。我如何做这项工作,为什么会出错?以下是相关的代码:

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

...然后调用以下函数......

def Pred_PSME(liLn):
    dbh = float(liLn[6])

以下是文件中的行:

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

我收到此错误消息:

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"

我在Ubuntu Linux计算机上使用Python 2.7。

1 个答案:

答案 0 :(得分:9)

您需要从字符串中删除双引号。这将为您提供float()可以转换的合法浮点字符串。