Skip to content Skip to sidebar Skip to footer

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?

Solution 1:

next(s for s in list_of_string if s)

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

Solution 2:

To remove all empty strings,

[s for s in list_of_strings if s]

To get the first non-empty string, simply create this list and get the first element, or use the lazy method as suggested by wuub.

Solution 3:

defget_nonempty(list_of_strings):
    for s in list_of_strings:
        if s:
            return s

Solution 4:

Here's a short way:

filter(None, list_of_strings)[0]

EDIT:

Here's a slightly longer way that is better:

from itertools import ifilter
ifilter(None, list_of_strings).next()

Solution 5:

to get the first non empty string in a list, you just have to loop over it and check if its not empty. that's all there is to it.

arr = ['','',2,"one"]
for i in arr:
    if i:
        print i
        break

Post a Comment for "Get First Non-empty String From A List In Python"