Erwin Hidayat
Erwin Hidayat

Reputation: 41

how can I concatenated string from a single list

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

Answers (2)

Eugenio
Eugenio

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

Ghost Ops
Ghost Ops

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

Related Questions