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?
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.
Solution: Use list comprehension [x for x in list if x] to filter the list and remove all lists that are empty.
Since a empty string is boolean False it will never go there unless you have at least a one-character string. Save this answer.
next(s for s in list_of_string if s)
Edit: py3k proof version as advised by Stephan202 in comments, thanks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With