-1

I'm trying to use python to search through a log file line by line. I want to capture the line that contains both strings "apple" and "banana".

Some lines contain only "apple" and likewise some lines contain only "banana". How do I check if the line contains BOTH strings, and then go into my next condition?

Here is how I'm doing it now and it's not working yet.

APPLE = "APPLE"
FAILURE_MSGS {
    APPLE: "apple"
}

for line in out.splitlines():
    if FAILURE_MSGS[APPLE] and "banana" in line:
        <do something special with this line>

Something to note that you might notice, "apple" is predefined from someone else's list of expected failure messages and I am looking to find "banana" also, but I'm not supposed to add it to the dict of FAILURE_MSGS.

What ends up happening is it is with every line that has '"apple"' or '"banana"', not just when it finds both. Not sure why..

Maggie S.
  • 1,076
  • 4
  • 20
  • 30
  • 3
    do you want `if FAILURE_MSGS[APPLE] in line and 'banana' in line: ...`? – mgilson Jun 15 '16 at 15:03
  • As @mgilson commented, you can't combine those two conditions by saying `if 'apple' and 'banana' in line:`. You have to spell out each condition separately: `if 'apple' in line and 'banana' in line:` – John Gordon Jun 15 '16 at 15:05

2 Answers2

2

You need to change your condition. Right now, you're testing to see if "apple" is true, and if "banana" is in the line. You'll end up with all the lines that contain "banana".

If you change it to:

if FAILURE_MSGS[APPLE] in line and "banana" in line:

then you should get the behavior you expect (processing only lines that contain both "apple" and "banana").

1

The correct code is:

for line in out.splitlines():
    if FAILURE_MSGS[APPLE] in line and "banana" in line:
         <do something special with this line>

What your code is doing:

  • if FAILURE_MSGS[APPLE] -- returns true because every nonempty string is true
  • if "banana" in line -- returns only true if banana in line

So you will get all lines that have "banana" -- regardless of "apple"

TehSphinX
  • 6,536
  • 1
  • 24
  • 34