Here is my task. Given a string consisting of n digits (single digits), between costs n-1 characters of operations, each of which can be either or -. Calculate the value of this expression. The program must print the result of the calculation of this expression Here is my code but it doesn't work
a = "1 5 3----2----9".replace(" ", " ").replace("----", "-")
print(int(str(a)))
ValueError: invalid literal for int() with base 10: '1 5 3-2-9'
CodePudding user response:
In Python, in order to evaluate an expression you have to use the eval()
function.
Side Note: The replace()
method returns a str
. So, you don't have to cast it to str
So, the resultant code is as follows
a = "1 5 3----2----9".replace(" ", " ").replace("----", "-")
print(eval(a))
Output
-2