So, I have this list
l = ['abc', 'retro', '', '', 'images', 'cool', '', 'end']
and, I want to join them in a way such as:
l = ['abc retro', '', '', 'images cool', '', 'end']
I tried lots of methods but nothing seemed to work. Any suggestions?
You can use itertools.groupby and a list comprehension. Group into ''s and non '' and join items from the latter using str.join. The ternary operator in the rear of the comprehension uses the group key to decide what to do for each group:
from itertools import groupby
l = ['abc','retro','','','images','cool','','end']
r = [j for k, g in groupby(l, lambda x: x=='')
for j in (g if k else (' '.join(g),))]
print(r)
# ['abc retro', '', '', 'images cool', '', 'end']
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