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

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 isnt your use of not, its that or doesnt mean what you think it does (and if you think it through, it couldnt):

if not (StatusRequest or StatusResponse) in line:

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

Put it in English: youre not trying to say if neither of these is in line. Python doesnt 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 isnt 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.)

Replace this line:

if not (StatusRequest or StatusResponse) in line:

With this one:

if StatusRequest not in line and StatusResponse not in line:

Not super elegant, but it will do the trick. Im not sure if theres a faster way to compare two strings against the same line.

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

You have to put each condition separately:

for line in readlines_data:
    if (StatusRequest not in line) and (StatusResponse not in line):
        result = line
        print(line)

Related posts:

Leave a Reply

Your email address will not be published.