title: How to parse AND/OR operator to evaluate a condition string in python
body: <p>If we have comparators <code>AND / OR</code> in a condition string such as</p>
  
  <pre><code>A != B AND C &gt; 100
  </code></pre>
  
  <p>how do I parse this string and evaluate the result so that the following code returns false</p>
  
  <pre><code>A = "foo" B = "foo" C = 99  -&gt;  eval("A != B AND C &gt; 100") is false
  </code></pre>
  
  <p>I use the operator library to do the evaluation and do a naive check, but if we see AND then we need to finish the evaluation on both sides before using the AND operator. Is there a better way to do the parsing &amp; evaluation?</p>
  
  <pre><code>import operator
  ops = {
      "AND": operator.and_,
      "OR": operator.or_,
      "==": operator.eq,
      "!=": operator.ne,
      "&lt;": operator.lt,
      "&lt;=": operator.le,
      "&gt;": operator.gt,
      "&gt;=": operator.ge 
  }
          result = false
          content = string.split(" ")
          for content in contents:
              if content in ops:
                      a = contents[i-1]
                      b = contents[i+1]
                  result = ops[content](a, b)
                  contents[i+1] = result
              i+=1
          if result is True:
              print("It is true")
  </code></pre>