Combining continuous new lines based on a list in Python

Question:

I am trying to create a function that will continuous new lines based on a list in Python.
For example, I have a list:
enter image description here

I want my function to output this:
enter image description here

I have a function already however its output is wrong:

final_list = list()
for sentence in test:
    if sentence != "rn":
        print(sentence)
        final_list.append(sentence)
    else:
        #Check if the next sentence is a newline as well
        curr_idx = test.index(sentence)
        curr_sentence = sentence
        next_idx = curr_idx + 1
        next_sentence = test[next_idx]
        times = 0
        while next_sentence == "rn":
            times += 1
            combine_newlines = next_sentence * times
            next_idx += 1
            next_sentence = test[next_idx]
            continue
        final_list.append(combine_newlines+ "rn")      

enter image description here

Thank you very much!

Asked By: gankmeplease

||

Answers:

test = [
    'I will be out',
    'I will have limited',
    'rn',
    'rn',
    'rn',
    'Thanks,',
    'rn',
    'Dave',
    'rn',
    'rn',
]

final_list = []
for e in test:
    if e != 'rn':
        final_list.append(e)
    else:
        if len(final_list) == 0 or not final_list[-1].endswith('rn'):
            final_list.append(e)
        else:
            final_list[-1] += e

prints

['I will be out', 'I will have limited', 'rnrnrn', 'Thanks,', 'rn', 'Dave', 'rnrn']

Explanation: Iterate over your items e in test, if they are not equal to rn, simply append them to the final_list, otherwise either append them to final_list or extend the last element in final_list based on if it ends with rn.

Answered By: Michael Hodel

You can use itertools.groupby to group consecutive items of the same value, and then join the grouped items for output:

from itertools import groupby

print([''.join(g) for _, g in groupby(test)])
Answered By: blhsing
test = [
    'I will be out',
    'I will have limited',
    'rn',
    'rn',
    'rn',
    'Thanks,',
    'rn',
    'Dave',
    'rn',
    'rn',
]

final_list = []
for e in test:
    if e != 'rn':
        final_list.append(e)
    else:
        if len(final_list) == 0 or not final_list[-1].endswith('rn'):
            final_list.append(e)
        else:
            final_list[-1] += e
Answered By: Alsadi Saleh11
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.