-1

I have a python object a="123.50" which is string type(a)=string I want something that tells me variable a is float object.

I have tried ast.literal_eval(value) , but since it accepts every other things.

Is there anything similar to it (ast.literal_eval) ?

Prashant Kumar
  • 2,057
  • 2
  • 9
  • 22
Suhas Kashyap
  • 398
  • 3
  • 14

2 Answers2

0

In python, its usual to just try it

>>> def floater(val):
...     try:
...             float(val)
...             return True
...     except ValueError:
...             return False
... 
>>> floater("123.45")
True
>>> floater("sinker")
False

Or you could just have python take a crack at it and report what it finds

>>> def what_is_it(val):
...     try:
...             return type(ast.literal_eval(val)).__name__
...     except:
...             return None
... 
>>> 
>>> what_is_it("113.44")
'float'
>>> what_is_it("1")
'int'
tdelaney
  • 73,364
  • 6
  • 83
  • 116
-1

You can refer PYTHON : There is a function similar to ast.literal_eval ()?.

  • 1
    What do you expect the [really dangerous `eval`](https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html) to do here that isn't covered by the safe `ast.literal_eval`? – Matthias Feb 17 '20 at 07:40
  • yes, you are correct, we can use ast module as well. eval is dangerous if we pass expressions. – niranjan patidar Feb 17 '20 at 07:50
  • 2
    You've edited your answer into something that doesn't answer the question - "Is there anything similar to it (ast.literal_eval) ?" – Sayse Feb 17 '20 at 08:10