Home  >  Article  >  Backend Development  >  How to remove empty strings in python

How to remove empty strings in python

王林
王林forward
2024-03-02 08:34:02494browse

How to remove empty strings in python

There are several ways to remove empty strings from strings :

  1. Use loops and conditional statements:
def remove_empty_strings(strings):
result = []
for string in strings:
if string != "":
result.append(string)
return result
  1. Use list comprehension:
def remove_empty_strings(strings):
return [string for string in strings if string != ""]
  1. Use filter function:
def remove_empty_strings(strings):
return list(filter(lambda string: string != "", strings))

You can remove empty strings from strings by calling these functions, for example:

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

Output:

['hello', 'world', 'Python']

The above is the detailed content of How to remove empty strings in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:lsjlt.com. If there is any infringement, please contact admin@php.cn delete