Home > Software engineering >  How can I turn a string that contains numbers and operators into a result?
How can I turn a string that contains numbers and operators into a result?

Time:09-30

I want to convert this string into a result n for the output to be 11.

a = "1 5*6/3"
print (a) 

CodePudding user response:

Can use eval() built-in function to evaluate a Python expression including any arithmetic expression.

a = "1 5*6/3"
b = eval(a)
print(b)

Output:

11.0

Using ast.literal_eval() as an alternative to eval()

The function eval() evaluates literal Python statements so should be used only if the input to evaluate is controlled and not untrusted user input. A safe alternative to eval() is using ast.literal_eval. Recent Python 3 versions disallows passing simple strings as an arugment and requires bulding an Abstract Syntax Tree (AST) then evalulating it against a grammar. See this answer that provides an example to evaluate simple arithmetic expressions safely.

CodePudding user response:

You can directly use the python eval function.

a = eval("1 5*6/3")
print(a)
  • Related