简体   繁体   中英

Multiple Conditions not working

I have the following code

if "[FAILED]" in line and (("Result:" not in line) or ("Date:" not in line)):
    print line

I'm reading a text file line by line. I want to look for anywhere in the text file "[FAILED] but it cant have "Result:" or "Date:" in the same line.

My code currently prints out the line even it has result or date in it.

Any help would be appreciated.

Thanks.

You need an and between the conditions in the parentheses.

Boolean logic is tricky, and if often helps to go through with examples. Consider this line:

FAILED blah blah Date: blah

So, going through your conditions one by one:

  • Failed is in the line, so let's check the next condition.
  • "Result:" is not in the line, so that part is true.
  • We've got an OR, and we already have a True result, so there's no need to even check if "Date:" is in the line.
  • So both sides of the AND are true, so the whole thing is true.

Obviously, exactly the same would happen if the line contained "Result:" but not "Date:".

If you had AND inside the parens, it would need to check that both "Date" was not in the line and "Result" is not in the line, rather than being happy if either were not there.

A different way to express the condition which might be clearer is this:

if "[FAILED]" in line and not (("Result:" in line) or ("Date:" in line)):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM