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:
- In python, how can I print lines that do NOT contain a certain string, rather than print lines which DO contain a certain string:
- shell – How to print lines between two patterns, inclusive or exclusive (in sed, AWK or Perl)?
- bash – Print lines with JUST grep on a string and nothing more?
- python – Print lines from file that contain a string
- How to print multiple lines of text with Python
- json – sed help: How to print a range of lines ONLY when found within another range of matched lines
- Functions: printing blank lines (Python)
- python – How to use one print statement yet still print on multiple lines
- dynamic – How to print the next N executed lines automatically in GDB?
- c – Reading lines from file, printing only lines that have same amount of letters as user will choose