Given:
a = 'aaa'
b = ''
c = 'ccc'
d = ''
e = 'eee'
list = (a, b, c, d, e)
How can I get a string using all the non empty elements of the list ?
Desired output:
'aaa,ccc,eee'
Using a generator expression:
",".join(string for string in lst if len(string) > 0)
The ",".join()
part is using the join()
method of strings, which takes an iterable argument and outputs a new string that concatenates the items using ","
as delimiter.
The generator expression between parenthesis is being used to filter empty strings out of the list.
The original list doesn't change.
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