How can I remove '
from the string '/'
and use it for division in Python?
For example:
a='/'
b=6
c=3
bac
The answer should be 2.
How can I remove '
from the string '/'
and use it for division in Python?
For example:
a='/'
b=6
c=3
bac
The answer should be 2.
You can get the built-in operators as functions from the operator
module:
import operator
a = operator.div
b = 6
c = 3
print a(b, c)
If you want to get the correct operator by the symbol, build a dict out of them:
ops = {
"/": operator.div,
"*": operator.mul,
# et cetera
}
a = ops["/"]
Python has an eval()
function that can do this:
a = "/"
b = "6"
c = "3"
print eval(b + a + c)
However, please note that if you're getting input from a remote source (like over a network), then passing such code to eval()
is potentially very dangerous. It would allow network users to execute arbitrary code on your server.
There are no single quotes in the variable a
. Python just uses these to denote a
represents a string
. b
and c
represent int
s and don't have the single quotes. If you ensure all of these variables are strings, you can join()
them together:
>>> a='/'
>>> b=6
>>> c=3
>>> bac = ''.join(str(x) for x in (b, a, c))
>>> bac
'6/3'
See how there are single quotes at the beginning and end of the string.
You could then use eval()
(with caution) to perform the division:
>>> eval(bac)
2