gpt4 book ai didi

python - python 将字符串转换为 float

转载 作者:行者123 更新时间:2023-12-01 09:26:23 25 4
gpt4 key购买 nike

为什么会抛出错误:ValueError:无法将字符串转换为 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

最佳答案

首先确定变量的格式。

带逗号的字符串无法使用“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

关于python - python 将字符串转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50352653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com