Question

I'm facing a problem in converting str to float. I do like in this post but this time it's not working because I have numbers in this format:

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

If I change the format (for example using 5.5 55 550 5500) it works fine. The Traceback states only:

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

What can I do? Is there a specific command?

my code is:

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

when I print avg_energySTR I get

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

THE ANSWER IS IN THE KOJIRO'S COMMENT

Était-ce utile?

La solution

You have a '\n' at one of the list cells.

So when the iteration is trying to convert '\n' to float it raise an ValueError

Try this code:

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)

You can also just split at the for itself:

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

Autres conseils

Change:

avg_energySTR = [str(i) for i in my_line.split(' ')]

To:

avg_energySTR = my_line.split()

From the comments, it appears that you have extra whitespace at the end of the line. If you use the default split algorithm (by passing no arguments, or by passing None), then trailing whitespace will be ignored.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top