我需要一个函数,它将python的运算符符号或关键字之一作为字符串,连同其操作数,对其进行求值,并返回结果.像这样:
>>> string_op('<=', 3, 3)
True
>>> string_op('|', 3, 5)
7
>>> string_op('and', 3, 5)
True
>>> string_op('+', 5, 7)
12
>>> string_op('-', -4)
4
Run Code Online (Sandbox Code Playgroud)
不能认为该字符串是安全的.我只对映射二元运算符感到满意,但如果能得到所有这些运算符,我会非常高兴.
import operator
def string_op(op, *args, **kwargs):
"""http://docs.python.org/2/library/operator.html"""
symbol_name_map = {
'<': 'lt',
'<=': 'le',
'==': 'eq',
'!=': 'ne',
'>=': 'ge',
'>': 'gt',
'not': 'not_',
'is': 'is_',
'is not': 'is_not',
'+': 'add', # conflict with concat
'&': 'and_', # (bitwise)
'/': 'div',
'//': 'floordiv',
'~': 'invert',
'%': 'mod',
'*': …Run Code Online (Sandbox Code Playgroud)