Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Value error when converting string to float

it is showing value error for converting string into float.
one of the line of my data file looks like this
100 1.2811559340137890E-003
I think maybe python can’t understand E while converting. also following is my code

import math
import matplotlib.pyplot as plt
x = []
y = []
f= open('C:/Users/Dell/assignment2/error_n.dat', 'r')
for line in f:
    line= line.split(' ')

    x.append(line[0])
    y.append(line[1])
for i in range(0,4):
    x[i]=float(x[i])
    x[i]=math.log(x[i])
    y[i]=float(y[i])
    y[i]=math.log(y[i])
        

plt.plot(y, x, marker = 'o', c = 'g')

plt.show()

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The string 1.2811559340137890E-003 can be converted to float without a problem. You can easily try this in the Python shell:

>>> s = '1.2811559340137890E-003'
>>> float(s)
0.001281155934013789

However, you’re actually trying to convert an empty string. See why:

>>> line = '100   1.2811559340137890E-003'
>>> line.split(' ')
['100', '', '', '1.2811559340137890E-003']

To solve your problem, simply change line.split(' ') to line.split():

>>> line.split()
['100', '1.2811559340137890E-003']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading