formelsammlung.strcalc module¶
-
formelsammlung.strcalc.
calculate_string
(expression)[source]¶ Calculate the given expression.
The given arithmetic expression string is parsed as an
ast
and then handled by theast.NodeVisitor
.Python exceptions are risen like with normal arithmetic expression e.g.
ZeroDivisionError
.Supported number types:
Warning
On PyPy3 only: When working with
complex
numbers containing or resulting withfloat
numbers be aware that the result ofcalculate_string()
and the equivalent arithmetic expression can divert in the decimals. The result fromcalculate_string()
is then less precise.Supported mathematical operators:
Positive (
operator.pos()
)+ a
Negative (
operator.neg()
)- a
Addition (
operator.add()
)a + b
Subtraction (
operator.sub()
)a - b
Multiplication (
operator.mul()
)a * b
Exponentiation (
operator.pow()
)a ** b
Division (
operator.truediv()
)a / b
FloorDivision (
operator.floordiv()
)a // b
Modulo (
operator.mod()
)a % b
How to use:
>>> calculate_string("(1+2)/3") 1.0