How to remove empty strings in python

王林
Release: 2024-03-02 08:34:02
forward
495 people have browsed it

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
Copy after login
  1. Use list comprehension:
def remove_empty_strings(strings):
return [string for string in strings if string != ""]
Copy after login
  1. Use filter function:
def remove_empty_strings(strings):
return list(filter(lambda string: string != "", strings))
Copy after login

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

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

Output:

['hello', 'world', 'Python']
Copy after login

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!

Related labels:
source:lsjlt.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template