How do I perform calculations with strings? Like suppose I have:
a=('/')
print(10, a, 5)
How do I get the answer as '2'? Because 10/5 is 2.
How do I perform calculations with strings? Like suppose I have:
a=('/')
print(10, a, 5)
How do I get the answer as '2'? Because 10/5 is 2.
There are multiple ways to do this.
The most common way, I guess, is using the operator module and a map (dictionary) to turn your strings into operators, as the next example.
import operator
run_ops = {
'+' : operator.add,
'-' : operator.sub,
'*' : operator.mul,
'/' : operator.truediv,
'%' : operator.mod,
'^' : operator.xor,
}.get
print(run_ops('/')(10, 5))
Or go with lambdas:
run_ops= {'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
# ...
'/': lambda x, y: x / y
}
run_ops['/'] (10,5)
Cheers
A nice method has been posted by epap.
However if you want to stick to the order of the expression where the "/", comes between the two numbers then one of the ways you can do it, is as below.
You can wrap (Number_1, "/", Number_2) and send it to a class and then print it. Something like below.
class Divide(object):
def __new__(cls, a, symbol, b):
result = None
if symbol == "/":
result = a/b
return result
print(Divide(5,"/",2))
This yields the below output
2.5
You can use "eval" to evaluate expressions given as strings.
a = "/"
res = eval("10" + a + "5")
print(res)