-2

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

a = "1+5*6/3"
print (a) 
CodeMonkey
  • 20,521
  • 4
  • 28
  • 71
Youcefdmd
  • 3
  • 2
  • You can use the built in function eval() https://towardsdatascience.com/python-eval-built-in-function-601f87db191, but I won't recommend you to use it often. – Ivan Dimitrov Sep 30 '21 at 14:42

2 Answers2

1

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

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

Output:

11.0

Using ast module 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 trusted user input. 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.

CodeMonkey
  • 20,521
  • 4
  • 28
  • 71
0

You can directly use the python eval function.

a = eval("1+5*6/3")
print(a)
veedata
  • 824
  • 1
  • 7
  • 13