开发者

convert string to pre defined python variable

I wanted to know How can I convert string to python defined variables.

Basically I want to do this.

if value1 operator value2:
      print True 

my operator is a string '==' , '>', '<', '!=' so that it becomes

if value1 == value2:
      print True

I 开发者_JAVA百科tried operator = getattr(sys.modules[__name__], operator ) but it work for class. thanks.


Using the operator module:

import operator

def op(str, value1, value2):
    lookup = {'==': operator.eq, '>': operator.gt,
              '<': operator.lt, '!=': operator.ne}
    if str in lookup:
        return lookup[str](value1, value2)

    return False

v1 = 1
v2 = 2
print op("!=", v1, v2)
# True


>>> import operator
>>> ops = {'==': operator.eq,
...        '>': operator.gt,
...        '<': operator.lt,
...        '!=': operator.ne}
>>> ops['=='](1,2)
False
>>> ops['=='](2,2)
True
>>> ops['>'](2,2)
False
>>> ops['>'](3,2)
True
>>> ops['!='](3,2)
True


I think you need to explicitly associate your operators with python's:

import operator as op

oper = '==' ## or '<', etc...
value1 = 1
value2 = 2

opdict = {'<': op.lt, '>': op.gt,
          '<=': op.le, '>=': op.ge,
          '==': op.eq, '!=': op.ne}

if opdict[oper](value1, value2):
    print true


if eval(repr(value1) + operator + repr(value2)):
     print True

or more simply

print eval(repr(value1) + operator + repr(value2))

Just be careful, eval gets a bad reputation =P (seriously tho, the solution with the operator module is probably a better choice)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜