0

I have a list of strings. I hope to print out the strings in the list that meet a condition. The list is as below:

In [5]: L = ["John and Mary", "Leslie", "Iva and Mark Li"]

I hope to print out each of the strings in L that has an and in it --

'John and Mary', 'Iva and Mark Li'

I have the following code:

In [6]: def grep(pattern, line):
            if pattern in line:
                print line

In [7]: [grep("and", I) for I in L]

This returns

John and Mary
Iva and Mark Li
Out[7]: [None, None, None]

What's the right way to do it? Thank you!!

yearntolearn
  • 944
  • 2
  • 13
  • 33
  • [If/else list comprehensions in Python](http://stackoverflow.com/questions/4260280/if-else-in-pythons-list-comprehension) would probably be a good post for you to see. – Skam Jul 23 '16 at 17:23

2 Answers2

5

Should be straight-forward:

>>> L = ["John and Mary", "Leslie", "Iva and Mark Li"]
>>> for s in L:
    if ' and ' in s: print(s)


John and Mary
Iva and Mark Li

If you want to capture the strings in a list, use a comprehension:

>>> [s for s in L if ' and ' in s]
['John and Mary', 'Iva and Mark Li']
John Coleman
  • 49,108
  • 7
  • 48
  • 110
5

Because your function does not have a return statement, it always returns None. You need to replace print with return.

OneCricketeer
  • 151,199
  • 17
  • 111
  • 216
Dartmouth
  • 1,060
  • 2
  • 16
  • 22