1

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 tried operator = getattr(sys.modules[__name__], operator ) but it work for class. thanks.

joaquin
86k31 gold badges146 silver badges155 bronze badges
asked Apr 6, 2011 at 4:35
1
  • The question is fine, but the title isn't very clear. Commented Apr 6, 2011 at 4:43

4 Answers 4

1

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
answered Apr 6, 2011 at 4:42
Sign up to request clarification or add additional context in comments.

Comments

0
>>> 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
answered Apr 6, 2011 at 4:41

Comments

0

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
answered Apr 6, 2011 at 4:41

Comments

0
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)

answered Apr 6, 2011 at 4:42

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.