Home > Back-end >  Value error when converting string to float
Value error when converting string to float

Time:02-15

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()

CodePudding user response:

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']

CodePudding user response:

I think the problem is that when you split that line, the second item (y) is "" (an empty string), and that's the one which can't be converted into a number.

CodePudding user response:

float is able to handle scientific notations. However from your description, it seems like the ValueError was thrown from trying to convert empty string to float.

'100   1.2811559340137890E-003'.split(' ')

will return

['100', '', '', '1.2811559340137890E-003']

You can check the string before converting it to float to handle such error.

  • Related