Strings and arithmetic operations

42 Views Asked by At

people. Can you please tell me how can I turn a string into arithmetic operation.

For example:

string_with_operation = "(23 + 3) / 4"

usual_operation = (23 + 3) / 4

I want a string_with_operation to be the same as usual_operation

I tried turn string_with_operation into an integer and a float but as expected it caused an error.

2

There are 2 best solutions below

1
olbapnairda On BEST ANSWER

In python can use eval() function

string_with_operation = "(23 + 3) / 4"

result = eval(string_with_operation)

print(result)

This is a good tutorial https://realpython.com/python-eval-function/#:~:text=You%20can%20use%20the%20built,it%20as%20a%20Python%20expression.

0
pixel On

I don't know which programming language you're using but in python, there's eval can help you.

here's the example you mentioned in action:

string_with_operation = "(23 + 3) / 4"

try:
    result = eval(string_with_operation)
    print(result)
except Exception as e:
    print(f"Error: {e}")

However, be careful when using eval() with untrusted input, as it can execute arbitrary code and pose security risks. If the input is not under your control, consider alternative ways to parse and evaluate expressions more safely.