-1

I am trying to read a text file that contains a lot of values. So first I append all the values to my list and my task is to find the sum of these values.

While appending I do something like: lst.append(float(values)).

I get an error since there are alphabetical strings like DNE in the values list.

So if value == 'DNE' how do I ignore that and let the program only focus on float values and add it.

For adding I know it's sum(lst), just wanted to know how to ignore that 'DNE'

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
Luke
  • 41
  • 1
  • 7

2 Answers2

2

When trying to convert a string to a numeric value you'll get a ValueError exception because that is not allowed. You need to wrap your append() call in a try-except block to catch these errors and handle them in an appropriate way:

A simple block of:

try:
    lst.append(float(value))
except ValueError:
    print "Cannot convert String to Float!"

should suffice.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
0

Use a try/except and ignore the specific exception raised when the value can not be converted to a float:

try:
    lst.append(float(values))
except ValueError as exc:
    pass
mhawke
  • 84,695
  • 9
  • 117
  • 138