我在将str转换为float时遇到问题。我喜欢this post中的内容,但是这次不起作用,因为我有以下格式的数字:

5.50000e+000 5.50000e+001 5.50000e+002 5.50000e+003


如果我更改格式(例如使用5.5 55 550 5500),则可以正常工作。追溯仅说明:

Traceback (most recent call last):
  File "phresREADER.py", line 27, in <module>
    tra = float(stri)
ValueError: could not convert string to float:


我能做什么?有特定的命令吗?

我的代码是:

my_line = f.readline()
avg_energySTR = [str(i) for i in my_line.split(' ')]
for stri in avg_energySTR:
        tra = float(stri)


当我打印avg_energySTR时,我得到

['5.50000e + 000','5.50000e + 001','5.50000e + 002','5.50000e + 003','\ n']

答案在小二郎的评论中

最佳答案

您在一个列表单元格中有一个'\n'

因此,当迭代尝试将'\n'转换为float时,会引发ValueError

试试这个代码:

avg_energySTR = "5.50000e+000 5.50000e+001 5.50000e+002 5.50000e+003"
avg_energySTR = [str(i) for i in avg_energySTR.split()]
avg_energy = []
for stri in avg_energySTR:
        tra = float(stri)
        avg_energy.append(tra)
print (avg_energy)


您也可以自行拆分:

avg_energySTR = "5.50000e+000 5.50000e+001 5.50000e+002 5.50000e+003 \n"
avg_energy = []
for stri in avg_energySTR.split():
       .......

关于python - 字符串未按预期转换为浮点型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23344345/

10-12 20:16