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

How do I convert a string to math in python?

So I want to convert a string to a math in python but am getting this error

string = "2 + 5"
math = int(string)
print(math)
>>> Should output 7 but instead outputs an error

How do I do it?

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 :

Instead of int() use eval():

string = "2 + 5"
math = eval(string)
print(math)

Or simply:

string = "2 + 5"
print(eval(string))
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