Get first non-empty string from a list in python

前端 未结 6 2231
轻奢々
轻奢々 2021-02-13 22:30

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?

相关标签:
6条回答
  • 2021-02-13 22:57

    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.

    0 讨论(0)
  • 2021-02-13 23:00
    def get_nonempty(list_of_strings):
        for s in list_of_strings:
            if s:
                return s
    
    0 讨论(0)
  • 2021-02-13 23:09

    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
    
    0 讨论(0)
  • 2021-02-13 23:11
    next(s for s in list_of_string if s)
    

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

    0 讨论(0)
  • 2021-02-13 23:20

    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.

    0 讨论(0)
  • 2021-02-13 23:22

    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()
    
    0 讨论(0)
提交回复
热议问题