Fabio Farago
Fabio Farago

Reputation: 23

Concatenate a list until a certain character

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,

Upvotes: 2

Views: 328

Answers (3)

user13341005
user13341005

Reputation: 11

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)

Upvotes: 0

demian-wolf
demian-wolf

Reputation: 1858

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)

Upvotes: 1

Bobby Ocean
Bobby Ocean

Reputation: 3326

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.

Upvotes: 0

Related Questions