Alex Rivera | Logout

Get first non-empty string from a list in python

Asked 2009-07-16T14:30:41.213
20

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?

Edit
Report

3 Answers

7

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.

answered 2009-07-16T14:33:08.917
1

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
answered 2009-07-16T14:47:29.777
0

Based on your question I'll have to assume a lot, but to "get" the first non-empty string:

(i for i, s in enumerate(x) if s).next()

which returns its index in the list. The 'x' binding points to your list of strings.

answered 2009-07-16T15:46:56.257

Your Answer