0

I need to convert a string variable in the form of 'x / y', where x and y are arbitrary values in this string, into a numerical value. I'd assume that, using python, simply doing float('x/y') would allow for the interpretation of the division operation and thus yield a numerical value as the response, but instead, I am met with the following error:

ValueError: could not convert string to float: '7/100' (7 and 100 were the arbitrary values here)

Which suggests that this method is invalid. Is there any other way of doing this ? I thought of converting 'x' into an integer, then 'y' into an integer, and dividing the two integer values, but surely there's a better way of doing this.

Skander Lejmi
  • 43
  • 1
  • 1
  • 4

1 Answers1

0
>>> a = '4/10'
>>> float(eval(a))
0.4

But I would be careful with eval . It's not safe, you could probably use ast.literal_eval() instead

Yiannis
  • 155
  • 1
  • 13