Home > Mobile >  how can I concatenated string from a single list
how can I concatenated string from a single list

Time:11-13

I'm new in python, I was wondering how can I concatenate string startswith 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']

Thank you

CodePudding user response:

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...

CodePudding user response:

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)
  • Related