2

I got a short question regarding python: How to do read specific lines from a file? By using multiple filters, bellow is my current code that doesn't show the expected results for me:

for line in loglist:
    if (str('send') and str('packet')) in line:
        print line

So, what I want is to print lines that contains both the words "send" and "packet", but it prints all lines that contain either send or packet.

many thanks in advance guys,

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
psilos
  • 21
  • 2
  • 1
    If you try the (str()..and..str()) expression in python shell, you recognize, that the result is "packet" alone, i.e. the last term due to the and operation enforcing evaluation of all terms. My intuitive approach would be a regular expression match, but even if this might be faster, it doesn't look prettier than the solution in the answer given, especially if the words may occur in any order. – guidot Oct 26 '12 at 14:47

4 Answers4

3

One way:

if all( x in line for x in ('send','packet')):

This is the most efficient way to do it if you need to scale up to an arbitrary number of conditions ...

Another way:

if ('send' in line) and ('packet' in line):

With just 2 checks, this is likely to be faster than the above.

mgilson
  • 300,191
  • 65
  • 633
  • 696
3

You should separate your conditions: -

if ('send' in line) and ('packet' in line):
    print line

If you do: -

if (str('send') and str('packet')) in line:

It is similar to saying: -

if 'packet' in line:

Because, the inner condition is and which returns the last false value, or if all are True, then returns the last value.

So, str('send') and str('packet') is equivalent to 'packet'

And you don't need that str wrapping around them.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
0

(str('send') and str('packet'))

Evaluates to "packet" with is always true (not what you want). Try

if "send" in line and "packet" in line

engineerC
  • 2,808
  • 17
  • 31
-1

(str('send') and str('packet')) evaluates to True. So you are saying True in line, which doesn't work of course. What you need is

if 'send' in line and 'packet' in line):
    print line

BTW, it makes no sense to run str() on a string, why would you convert a string to a string?

BrtH
  • 2,610
  • 16
  • 27