In python, how can I print lines that do NOT contain a certain string, rather than print lines which DO contain a certain string:

The problem isn’t your use of not, it’s that or doesn’t mean what you think it does (and if you think it through, it couldn’t):

if not ("StatusRequest" or "StatusResponse") in line:

You’re asking whether the expression ("StatusRequest" or "StatusResponse") appears in line. But that expression is just the same thing as "StatusRequest".

Put it in English: you’re not trying to say “if neither of these is in line”. Python doesn’t have a neither/none function, but it does have an any function, so you can do this:

if not any(value in line for value in ("StatusRequest", "StatusResponse")):

This isn’t quite as nice as English; in English, you can just say “if none of the values ‘StatusRequest’ and ‘StatusResponse’ are in line”, but in Python, you have to say “if none of the values coming up are in line, for values ‘StatusRequest’ and ‘StatusResponse'”.

Or, maybe more simply in this case:

if "StatusRequest" not in line and "StatusResponse" not in line:

(Also, notice that you can use not in, instead of using in and then negating the whole thing.)

Leave a Comment