I'm wondering if it is possible to do that?
s = "> 4"
if 5 s:
print("Yes it is.")
I'm wondering if it is possible to do that?
s = "> 4"
if 5 s:
print("Yes it is.")
You want eval
.
s = "> 4"
if eval("5"+s):
print("Yes it is.")
Here is the documentation on eval
.
Note that if you don't know what, exactly, is in your input string, eval
is extremely insecure. Use with caution.
This can easily be done using eval()
. However, eval()
is pretty dangerous and is best avoided.
For other ideas, see Safe expression parser in Python
I think the best approach depends on where s
comes from:
1) If it's user input, you certainly don't want to use eval()
. An expression parser is probably the way to go.
2) If s
is set programmatically, you're probably better off turning it into a function:
pred = lambda x:x > 4
if pred(5):
print("Yes it is.")
Assuming that what you really want to do is store the comparison "> 4" and use it somewhere, I would suggest something like the following:
import operator
class Comparison(object):
def __init__(self, operator, value):
self.operator = operator
self.value = value
def apply(self, value):
return self.operator(value, self.value)
s = Comparison(operator.gt, 4)
if s.apply(5):
print("Yes it is.")