Skip to content
Related Articles

Related Articles

Python – Evaluate Expression given in String

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 27 Jul, 2021
View Discussion
Improve Article
Save Article

Sometimes, while working with Python Strings, we can have certain computations in string format and we need to formulate its result. This can occur in domains related to Mathematics and data. Let’s discuss certain ways in which we can perform this task.

Method #1 : Using regex + map() + sum() 
The combination of above functions can be used to solve this problem. In this, we perform the task of computation using sum() and mapping of operator and operation using map(). This method can be used if the string has only + or -. Method #2 can be used for other operations as well.

Python3




# Python3 code to demonstrate working of
# Expression evaluation in String
# Using regex + map() + sum()
import re
 
# initializing string
test_str = "45 + 98-10"
 
# printing original string
print("The original string is : " + test_str)
 
# Expression evaluation in String
# Using regex + map() + sum()
res = sum(map(int, re.findall(r'[+-]?\d+', test_str)))
 
# printing result
print("The evaluated result is : " + str(res))

Output : 

The original string is : 45+98-10
The evaluated result is : 133

 

Method #2 : Using eval() 
This is one of the way in which this task can be performed. In this, we perform computation internally using eval(). 

Python3




# Python3 code to demonstrate working of
# Expression evaluation in String
# Using eval()
 
# initializing string
test_str = "45 + 98-10"
 
# printing original string
print("The original string is : " + test_str)
 
# Expression evaluation in String
# Using eval()
res = eval(test_str)
 
# printing result
print("The evaluated result is : " + str(res))

Output : 

The original string is : 45+98-10
The evaluated result is : 133

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!