新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

python怎么去除空字符串,python去除空白字符

发布时间:2023-10-31 20:44:56

python怎样去除空字符串

有几种方法可以去除字符串中的空字符串:

  1. 使用循环和条件语句:
def remove_empty_strings(strings):
    result = []
    for string in strings:
        if string != "":
            result.append(string)
    return result
  1. 使用列表推导式:
def remove_empty_strings(strings):
    return [string for string in strings if string != ""]
  1. 使用filter函数:
def remove_empty_strings(strings):
    return list(filter(lambda string: string != "", strings))

可以通过调用这些函数来去除字符串中的空字符串,例如:

strings = ["hello", "", "world", "", "python"]
result = remove_empty_strings(strings)
print(result)

输出:

['hello', 'world', 'python']