-6 python
如何'
从字符串中删除'/'
并将其用于Python中的除法?
例如:
a='/'
b=6
c=3
bac
Run Code Online (Sandbox Code Playgroud)
答案应该是2.
您可以将内置运算符作为operator
模块中的函数:
import operator
a = operator.div
b = 6
c = 3
print a(b, c)
Run Code Online (Sandbox Code Playgroud)
如果您想通过符号获取正确的运算符,请从中构建一个dict:
ops = {
"/": operator.div,
"*": operator.mul,
# et cetera
}
a = ops["/"]
Run Code Online (Sandbox Code Playgroud)