2

I've this if statment that must check if this two string are present on self.line.lower() that can be ex: 123abc567 or blaxyzbla:

        if 'abc' or 'xyz' in self.line.lower():
            print ('Present')
        else:
            print ('Not Present')

why this return me ever true(Print Present), if the self.line.lower() doesn't contain the abc or xyz in the string?

I must use this to work:

     if self.line.lower().find('abc') != -1:
        print ('Present')
     elif self.line.lower().find('xyz') != -1:
        print ('Present')
     else:
        print ('Not Present')   

Thanks a lot.

ah bon
  • 9,293
  • 12
  • 65
  • 148
rocherz
  • 31
  • 1
  • 2
  • 7

2 Answers2

7

What you had was equivalent to:

if 'abc' or ('xyz' in self.line.lower()):

Order of precedence table can be found in this Python documentation. At the bottom of the chart you will see in has higher precedence than or (or and) therefore 'xyz' was checked to be in self.line.lower() and then that result was or'ed with 'abc'. Since 'abc' evaluates to a non-zero value the entire expression would always be true.

One way I can think of doing this neatly is as a nested for in that looks for the items in the target list against the string we are searching.

if any(x in line.lower() for x in ['abc', 'xyz']):
    print ('Present')
else:
    print ('Not Present')

x in line.lower() for x in ['abc', 'xyz'] produces a generator that will return true or false for each element. You use any to figure out if any of the elements in the generated list are true meaning at least one of them was found. If you wanted to check if all of the items are found in the string you can replace any with all.

Michael Petch
  • 46,082
  • 8
  • 107
  • 198
  • This work only if i find strict string 'abc' or 'xyz', but not work if i check presence on string: 123abc456 or blaxyzbla – rocherz Sep 27 '14 at 03:23
  • You are correct. Even if we account for precedence it still isn't going to do what you want. I have provided a one liner that should do what you want. – Michael Petch Sep 27 '14 at 03:32
  • thanks a lot, with this method works :) – rocherz Sep 27 '14 at 03:46
  • Not a problem. I also added a bit about replacing 'any` with 'all' if you wanted to know if ALL the strings you were checking for were in the line. – Michael Petch Sep 27 '14 at 03:47
0
if 'abc' or 'xyz' in self.line.lower():

is being broken into two different conditionals, which are then evaluated together with or.

  • 'abc'
  • 'xyz' in self.line.lower()

The first of the two will always evaluate as True, because it's not an empty string.

So you have if True or 'xyz' in self.line.lower() which will always evaluate to true. For this reason, your code will always print ('Present') and never print ('Not Present').

I think you'd like to use

if 'abc' in self.line.lower() or 'xyz' in self.line.lower():
    print('Present')
else:
    print('Not Present')
BUSY
  • 180
  • 6