Skip to main content
 首页 » 编程设计

python之为什么在使用过滤器时 "return s and s.strip()"有效

2025年05月04日23arxive

<分区>

def not_empty(s): 
    return s and s.strip() 
 
list(filter(not_empty, ['A', '', 'B', None, 'C', '  '])) 
# result: ['A', 'B', 'C'] 

我不知道为什么会这样。 我知道:x 和 y 如果 x 为假,则 x,否则 y。 所以首先是 return 'A' 和 'A'.strip()。 但这显示在 python IDLE 中

>>>'A' is True 
False 
>>>'A' is False 
False 

所以。 not_empty('A') 返回'A',对吗? 'A' 不是 True,为什么会出现在结果中?

为什么

not_empty(' ')
''

' ' 也是假的。

>>>' ' is True 
False 
>>>' ' is False 
False