2

I have a string with mathematical operations, how do I evaluate the string within [] to generate the output shown below?

mystring = "[2*3-1] plus [4+2] is equal to [5+6]."

re.findall(r"\[(.*?)\]",mystring) # to find 2*3-1, 4+2, 5+6

Output: "5 plus 6 is equal to 11." # expected output. 

1 Answer 1

3

You may use re.sub with eval and a callback function here:

mystring = "[2*3-1] plus [4+2] is equal to [5+6]."
output = re.sub(r'\[(.*?)\]', lambda m: str(eval(m.group(1))), mystring)
print(output)  # 5 plus 6 is equal to 11.

The strategy here is to match the aritrmetic expression inside every [...], which then gets passed to a lambda function. There, we call eval() to get the result, cast to a string and generate the replacement.

Sign up to request clarification or add additional context in comments.

4 Comments

++ but OP doesn't need [ and ] in output
@anubhava On a cell phone with bad visibility to the entire screen at once, sorry.
You wrote this formatted code on a mobile, wish I could give 10 ++ to you
Still trying to find a software shop where mobile typing skills gets you promoted :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.