2

I'm wondering if it is possible to do that?

s = "> 4"
if 5 s:
    print("Yes it is.")
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
okobaka
  • 576
  • 4
  • 8
  • 2
    Why do you want to do that? There is probably a better way to do what you need to do. – BrenBarn Mar 06 '13 at 07:37
  • I have string that will be changed, like set of options, and each option represents condition. - oh and "condition string" is generated by someone else - AI. – okobaka Mar 06 '13 at 07:44

3 Answers3

3

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.

Kyle Strand
  • 15,941
  • 8
  • 72
  • 167
3

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.")
Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Hm, I'm always concern about security issue i think i will `"> 5".split(' ')` and match (>, <, >=, <=) and int([1]) – okobaka Mar 06 '13 at 08:00
  • But if you use split, you're assuming that there will be a space in the input. `">5"` is a perfectly valid comparison, but `split` won't help you extract the operator. – Kyle Strand Mar 06 '13 at 21:11
  • I do, good point to remember. I know, i will have to `if` all cases. – okobaka Mar 07 '13 at 09:43
3

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.")
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306