Linux 拨号vps windows公众号手机端

python怎么去除空字符串

lewis 8年前 (2017-11-17) 阅读数 8 #程序编程
文章标签 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']
版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门