1

I want a String to be converted to a float and if the string contains a calculation (like 1/3) it should calculate it and then convert.

I've tried by entering float(y), whereas y is my '+1/3'.

y = '+1/3'
float(y)

I expected the output to be something like '0.3333', but the error message i keep getting is "ValueError: could not convert string to float: '+1/3'".

Tiiill
  • 47
  • 1
  • 3

2 Answers2

0

have you tried with eval?

eval("+1/3")

output

0.3333333333333333
NicoT
  • 341
  • 2
  • 11
  • using eval is not a good practice, you read more about that [here](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice). – lmiguelvargasf Sep 10 '19 at 20:22
0

Let's assume you are going to have / in your string, so you can use the following code:

numerator, denominator = '+1/3'.split('/')
y = float(numerator) / float(denominator)
lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228