Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I cannot convert str to int because of the error

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’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading