如果需要从列表中排除空字符串(‘’)和包含空格、制表符、换行符等空白字符的字符串,可以先使用strip()方法去掉字符串两端的空白字符,然后再使用filter()函数和lambda表达式过滤掉空字符串。
示例如下:
list1 = ['', '', ' \ntitle1 \n', '\t title2\n \n \n']
# 使用列表推导式和strip()方法去掉空白字符
list1 = [s.strip() for s in list1]
# 使用filter()函数和lambda表达式过滤掉空字符串
list1 = list(filter(lambda x: x != '', list1))
print(list1) # 输出:['hello', 'hello']
首先使用列表推导式和strip()方法去掉每个元素两端的空白字符,生成一个新的列表。然后使用filter()函数和lambda表达式过滤掉空字符串,得到一个新的只包含非空字符串的列表。最后输出结果为:
['title1', 'title2']
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格
python字符串处理去空格 python字符串处理去空格 python字符串处理去空格 python字符串处理去空格 python字符串处理去空格 python字符串处理去空格