Can we do math operation on Python Strings?

PythonServer Side ProgrammingProgramming

You can use the eval function to evaluate mathematical expressions in strings.

Example

For example, if you have a string with the content (4*5) + 21, you can eval it and get the result.

>>> s = "(4*5) + 22"
>>> eval(s)
42

Eval follows Python rules for evaluating mathematical expressions for cases in which parenthesis are not provided, etc. Be very careful when using eval though as it can be a source of huge security loopholes and bugs.

raja
Published on 18-Dec-2017 12:20:59
Advertisements