s and s.strip()“ 这个表达式的值。Python语法是这么运行的:
如果s is None,那么s会被判断为False。而False不管和什么做and,结果都是False,所以不需要看and后面的表达式,直接返回s(注意不是返回False)。
如果s is not None,那么s会被判断为True,而True不管和什么and都返回后一项。于是就返回了s.strip()。
所以s.strip() 不能单独使用,语法是有问题的
>>> def not_empty(s): return s.strip() >>> list(filter(not_empty,['A','','B','C',None,' '])) Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> list(filter(not_empty,['A','','B','C',None,' '])) File "<pyshell#16>", line 2, in not_empty return s.strip() AttributeError: 'NoneType' object has no attribute 'strip'
正确用法:
>>> def not_empty(s): return s and s.strip() >>> list(filter(not_empty,['A','','B','C',None,' '])) ['A', 'B', 'C']