Search code examples
stringnumbersoperation

Strings and arithmetic operations


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.


Solution

  • 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.