I want to convert this string into a result n for the output to be 11.
a = "1+5*6/3"
print (a)
I want to convert this string into a result n for the output to be 11.
a = "1+5*6/3"
print (a)
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.