2

I have this variable assignation in my code which take data from web and converts it to float (after extracting numbers only)

variable_1 = float(re.sub('[^0-9]','', basic_data_list[17]))

Now if there is no data on the web (which is specified by "-") I get the error

ValueError: could not convert string to float: which is expected.

Is there any way I can get the value zero assigned to this variable if no data is available? Is there any equivalent of Excels's IsError in python?

Stelios
  • 119
  • 3
  • 11

2 Answers2

3

First, for a float, you probably should accept . and - :

variable_1 = float(re.sub('[^0-9\-\.]','', basic_data_list[17]))

Otherwise :

float(re.sub('[^0-9]','', '-3.5'))

would return

35.0

Then :

variable_1 = float(re.sub('[^0-9\-\.]','', 'abc'))

raises a ValueError.

You could use a try block. There's even an example in the documentation which directly describes your problem :

>>> while True:
...     try:
...         x = int(raw_input("Please enter a number: "))
...         break
...     except ValueError:
...         print "Oops!  That was no valid number.  Try again..."

In the except ValueError part, you could define variable_1 as you wish. Note that 0 is not always the best value to assign for "not a number" :

try:
  variable_1 = float(re.sub('[^0-9\-\.]','', basic_data_list[17]))
except ValueError:
  variable_1 = 0.0
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
2

str.isnumeric() works on unicode strings. so if you use:

unicode(basic_data_list[17]).isnumeric()

you'll get a boolean value - True for numeric and False for non-numeric values.

so i'm thinking something along these lines will work:

variable_1 = float(re.sub('[^0-9]','', basic_data_list[17] if unicode(basic_data_list[17]).isnumeric() else "0"))

from your reply i'm guessing youre using python 3. heres what i found: NameError: global name 'unicode' is not defined - in Python 3

you should be able to use this by replacing "unicode" with "str"

Community
  • 1
  • 1
antonmik
  • 103
  • 1
  • 8