把一个序列中的空字符串删掉,可以这么写(参见廖雪峰的python3教程)
def not_empty(s):
return s and s.strip()
list(filter(not_empty, ['A', '', 'B', None, 'C', ' ']))
# 结果: ['A', 'B', 'C']
其中:filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象。此函数接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。 格式:filter(function, iterable)
而strip()函数用于移除字符串头尾指定的字符(默认为空格)或字符序列。
重点在于如何理解 return s and s.strip(),之前一直想为什么不直接返回s.strip()。
如果s is None,那么s会被判断为False。而False不管和什么做and,结果都是False,所以不需要看and后面的表达式,直接返回s(注意不是返回False)。
如果s is not None,那么s会被判断为True,而True不管和什么and都返回后一项。于是就返回了s.strip()。
因为filter()就是将函数逐一作用于元素上,所以将filter的作用拆分如下:
def not_empty(s):
return s and s.strip()
print(not_empty("A"), not_empty(""), not_empty("B"), not_empty(None), not_empty("C"), not_empty(" "))
结果为:A B None C
def not_empty(s):
return s and s.strip()
print(bool(not_empty("A")), bool(not_empty("")), bool(not_empty("B")), bool(not_empty(None)), bool(not_empty("C")), bool(not_empty(" ")))
结果为:True False True False True False
由以上便可以理解return s and s.strip()了。