Concatenate a list until a certain character

Viewed 113

I have this list:

Jokes =   ['First joke', 'Still first', '', 'Second Joke', 'Still second joke', 'Still 2nd joke']

I would want to concatenate the list as follow:

Jokes = ['First joke \n Still first', 'Second joke \n Still second joke \n Still 2nd joke']

Is this somehow possible?

Thank you,

3 Answers

Here is an example solution:

jokes = ['First joke', 'Still first', '', 'Second Joke', 'Still second joke', 'Still 2nd joke']

groups = [[]]
for part in jokes:
    if part:
        groups[-1].append(part)
    else:
        groups.append([])

result = [' \n '.join(joke) for joke in groups]
print(result)
jokes = ['First joke', 'Still first', '', 'Second Joke', 'Still second joke', 'Still 2nd joke']
jokes2 = []
for i in range(len(jokes) // 2):
    jokes2.append(jokes[2 * i] + ' \n ' + jokes[2 * i + 1])
print(jokes2)

What criteria are you using to determine when to split. Are you using the ''? Are you expecting exactly the phrase "first joke" "second joke"? You don't tell us your criteria, so we are guessing. Suppose it is the ''.

Jokes = ['First joke', 'Still first', '', 'Second Joke', 'Still second joke', 'Still 2nd joke']
idx   = Jokes.index('')
Jokes = ['\n'.join(Jokes[:idx]),'\n'.join(Jokes[idx+1:])]
print(Jokes)

If you have a longer list or more than one '', then this answer obviously changes. But I have no details, so I don't know.

Related