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
-
The question is fine, but the title isn't very clear.Andrew Jaffe– Andrew Jaffe2011年04月06日 04:43:54 +00:00Commented Apr 6, 2011 at 4:43
4 Answers 4
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
Nick Presta
28.8k6 gold badges61 silver badges76 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
>>> 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
John La Rooy
306k54 gold badges378 silver badges514 bronze badges
Comments
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
Andrew Jaffe
27.2k4 gold badges54 silver badges59 bronze badges
Comments
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
jon_darkstar
16.9k7 gold badges35 silver badges38 bronze badges
Comments
lang-py