Python – Evaluate Expression given in String

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. Lets 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().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Expression evalution 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 evalution 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)) 

chevron_right


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().

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output :

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.