How can I turn a string that contains numbers and operators into a result?

Question:

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

a = "1+5*6/3"
print (a) 
Asked By: Youcefdmd

||

Answers:

The eval() built-in function can evaluate a Python expression including any arithmetic expression. But note the eval() function is a security concern because it can evaluate any arbitrary Python expression or statement so should be used only if the input to evaluate is controlled and trusted user input. There are examples to why eval() is dangerous in this question.

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

Output:

11.0

Using ast module as an alternative to eval()

A safe alternative to eval() is using ast.literal_eval. Recent Python 3 versions disallows passing simple strings to ast.literal_eval() as an argument. Now must parse the string to buld an Abstract Syntax Tree (AST) then evaluate it against a grammar. This related answer provides an example to evaluate simple arithmetic expressions safely.

Answered By: CodeMonkey

You can directly use the python eval function.

a = eval("1+5*6/3")
print(a)
Answered By: veedata
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.