python去掉列表中的空格、空值、标点符号
作者:YXN-python 阅读量:8 发布日期:2024-02-29
import re
def clean_list_elements(lst):
cleaned_list = []
# 定义一个正则表达式模式,用于匹配标点符号
punctuation_pattern = r'[^\w\s]'
for element in lst:
if isinstance(element, str): # 确保元素是字符串
# 移除标点符号
cleaned_element = re.sub(punctuation_pattern, '', element)
# 移除前后空格和中间空白符
cleaned_element = cleaned_element.strip()
cleaned_element = re.sub(r'\s+', '', cleaned_element)
if cleaned_element: # 检查是否为空字符串
cleaned_list.append(cleaned_element)
elif element is not None: # 处理空值
# 对于非字符串但非空的元素,仅移除None
cleaned_list.append(element)
return cleaned_list
input_list = [' apple ', 'orange!', '', 'pear,', None, 'banana ', ' ', 'grape...']
result = clean_list_elements(input_list)
print(result)
# 输出:['apple', 'orange', 'pear', 'banana', 'grape']
YXN-python
2024-02-29