Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first non-empty string from a list in python

In Python I have a list of strings, some of which may be the empty string. What's the best way to get the first non-empty string?

like image 856
Simon D Avatar asked Jul 16 '09 14:07

Simon D


People also ask

How do you remove Blank strings from a list of strings in Python?

Method #1: Using remove() This particular method is quite naive and not recommended use, but is indeed a method to perform this task. remove() generally removes the first occurrence of an empty string and we keep iterating this process until no empty string is found in list.

How do you ignore an empty list in Python?

Solution: Use list comprehension [x for x in list if x] to filter the list and remove all lists that are empty.

Can you index an empty string?

Since a empty string is boolean False it will never go there unless you have at least a one-character string. Save this answer.


1 Answers

next(s for s in list_of_string if s)

Edit: py3k proof version as advised by Stephan202 in comments, thanks.

like image 133
Wojciech Bederski Avatar answered Sep 22 '22 11:09

Wojciech Bederski