How to concatenate items in a list?

Viewed 651

I want to concatenate items in a list if the last character of the list is not a "."

l=["First item","Second item","Third item.","Fourth item."]

abc=[element for element in l if not element[-1]=="."]

I tried to use a list comprehension but I don't know how to concatenate two items using list comprehension.

What I want:

abc=["First itemSecond itemThird item.","Fourth item."]
4 Answers

Loop over your list items, building strings. Whenever the current item ends in a period, append the currently built string to the final result, and start building a new string:

l=["First item","Second item","Third item.","Fourth item."]

result = []
curr_str = ""
for item in l:
    curr_str += item
    if item[-1] == ".":
        result.append(curr_str)
        curr_str = ""

 ['First itemSecond itemThird item.', 'Fourth item.']

now this is a messy answer but i'd expect it to work:

w = ''.join(l).split('.')
x = [item + '.' for item in w]

As per documentation https://docs.python.org/3/library/stdtypes.html#str.join

l=["First item","Second item","Third item.","Fourth item."] abc=[element for element in l if not element[-1]=="."]

Add one more line abc = [" ".join(x for x in abc)] abc will still be a list having result

you can join and split:

l=["First item","Second item","Third item.","Fourth item."]
new_l = [element.lstrip()+'.' for element in ' '.join(l).split('.')][:-1]

Output new_l:

['First item Second item Third item.', 'Fourth item.']
Related