Reputation: 41
I'm new in python, I was wondering how can I concatenate string starts with certain character (Eg.'g') in a list with the string after that. for example :
list = ['green', 'black', 'brown', 'yellow', 'red', 'pink', 'glow', 'big']
And the result I expected is :
new_list = ['green black', 'brown', 'yellow', 'red', 'pink', 'glow big']
Upvotes: 1
Views: 54
Reputation: 193
I'd do it like this:
list = ['green', 'black', 'brown', 'yellow', 'red', 'pink', 'glow', 'big']
new_list = []
agrega = True
for i in range(len(list)):
if agrega == False:
agrega = True
continue
agrega = True
if list[i].startswith('g'):
new_list.append(list [i] + " " + list [i+1] )
agrega = False
else:
if agrega:
new_list.append(list[i])
print (new_list)
Upvotes: 0
Reputation: 1734
Try this code
lst = ['green', 'black', 'brown', 'yellow', 'red', 'pink', 'glow', 'big']
for i, j in enumerate(lst):
if j.startswith('g'):
lst[i] = f'{j} {lst[i+1]}'
del lst[i+1]
print(lst)
Outputs:
['green black', 'brown', 'yellow', 'red', 'pink', 'glow big']
Tell me if its not working...
Upvotes: 1