带有隐藏'的字符串字符无法转换为float

时间:2016-03-10 17:39:36

标签: string python-2.7 character

读取csv文件,遇到隐藏'的字符串可以这么说,字符串的长度比打印字符串时出现的长。最终我需要将字符串转换为浮点数。怎么办呢?运行Python 2.7.10 :: Anaconda 2.3.0(x86_64)

代码:

    f=open('Archive_2016-02-23.csv','r')
    for line in f:
        if 'Instrument' in line: #test if header line
            continue #skip header line
    for f,b in zip(l_headers, line.split(',')):
        globals()[f]=b   #makes each header name into a variable with values
    print WPrcAvg, len(WPrcAvg), type(WPrcAvg)
    for i in WPrcAvg:
        print 'i: ', i
    WPrcAvg=WPrcAvg.replace(' ','')
    for i in WPrcAvg:
        print 'i: ', i
    print WPrcAvg, float(WPrcAvg)  #here is where error breaks the code

结果:

2.707 11 <type 'str'>
i:  
i:  2
i:  
i:  .
i:  
i:  7
i:  
i:  0
i:  
i:  7
i:  
i:  
i:  2
i:  
i:  .
i:  
i:  7
i:  
i:  0
i:  
i:  7
i:  
2.707
Traceback (most recent call last):
  File "readtest.py", line 35, in <module>
    print WPrcAvg, float(WPrcAvg)  #here is where error breaks the code
ValueError: could not convert string to float: 

1 个答案:

答案 0 :(得分:0)

一位同事建议使用此代码,它对我有用。不是我理解&#34;如何&#34;和&#34;为什么&#34;它,但这有效...

with open('Archive_2016-02-23.csv','rb') as f:
    reader = csv.reader( (line.replace('\0','') for line in f) )
    reader.next()
    for row in reader:
        for f,b in zip(l_headers, row):
            globals()[f]=b   #makes each header name into a variable with values