有条件地在python中打印出行

时间:2016-07-23 17:14:49

标签: python string generator

我有一个字符串列表。我希望打印出符合条件的列表中的字符串。清单如下:

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

我希望打印出L中包含and的每个字符串 -

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

我有以下代码:

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

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

返回

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

这样做的正确方法是什么?谢谢!!

2 个答案:

答案 0 :(得分:5)

应该是直截了当的:

select
sum(case when total cost is not null then 1 else
    case when customer = 'New Customer' then 1 else
    case when sales like 's%' then 1 else
    end end end
from table
where date between '7/20/2016' and '7/21/2016'

如果要捕获列表中的字符串,请使用理解:

>>> 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

答案 1 :(得分:5)

因为你的函数没有return语句,所以它总是返回None。您需要将print替换为return