将str转换为float python

时间:2018-05-15 14:22:01

标签: python type-conversion

为什么会抛出错误:ValueError: could not convert string to float:

frequencies.append(float(l[start+1:stop1].strip())) 
losses.append(float(l[stop1+5:stop2].strip()))

float()命令不会将值解析为float类型吗?我错在哪里?频率和损耗都是列表

这是代码:

def Capture():
impedance = 0 
losses = [] 
frequencies = [] 
Xtalk = []
start = 0
stop1 = 0
stop2 =0
for filename in glob.glob(os.path.join(user_input, '*.txt')):
    with open(filename, 'r') as f: 
        for l in f.readlines(): 
            if l.startswith(' Impedance'): 
                v = l[12:-7] 
                impedance = float(v) 
            if l.startswith(' Xtalk'): 
                Xtalk.append(l[7:].strip()) 
            if l.startswith(' Loss per inch'): 
                start = l.find('@') 
                stop1 = l.find('GHz', start) 
                stop2 = l.find('dB', start) 
            frequencies.append(float(l[start+1:stop1].strip())) 
            losses.append(float(l[stop1+5:stop2].strip())) 
print(impedance, frequencies, losses, Xtalk)

它基本上从文本文件中获取值并将它们打印到控制台上 文本文件如下所示:

    Impedance = 71.28 ohms

Begin Post processing
Frequency multiplier = 1Hz
number of ports = 12
Start Frequency = 0
End Frequency = 40000000000
Number of Frequency points = 4001
Touchstone Output file = C:\Users\Aravind_Sampathkumar\Desktop\IMLC\BO\Output_TW_3.5-TS_3-core_h_2.xml_5000mil.s12p
Output format = Real - Imaginary
Loss per inch @ 2.500000e+00 GHz = -0.569 dB
Loss per inch @ 5 GHz = -0.997 dB
Xtalk #1 (Conductor 1  2):
    Step response Next= -0.56 mV
    Step response Fext peak @ 5 inches= 0.11 mV
Xtalk #2 (Conductor 5  6):
    Step response Next= -0.56 mV
    Step response Fext peak @ 5 inches= 0.11 mV
Finished post processing

1 个答案:

答案 0 :(得分:1)

首先确保哪个是变量的格式。

带逗号的

字符串无法使用“float()”解析器转换为float

a = "1,2345"
float(a)
Traceback (most recent call last):
   File "<input>", line 1, in <module>
ValueError: could not convert string to float: '1,2345'
a = "1.2345"
float(a)
1.2345