Home > Net >  Concatenate items in a python list if '\\' is at the end of item
Concatenate items in a python list if '\\' is at the end of item

Time:01-23

I need to merge with next item in a list if previous item has '\' at the end. Example:

original_list = ['first.key=First value', 'second.key=Second value, first line\\', 
'Second value, second line\\', 'Second value, third line\\', 'Second value, fourth 
line', 'third.key=Third value']

Expected result is:

desired_list = ['first.key=First value', 'second.key=Second value,first line\\ Second 
value, second line\\ Second value, third line\\ Second value, fourth line', 
'third.key=Third value']

Do not assume that the first item ending with '\' is the second item in the list. I dont know which will it be.

CodePudding user response:

It is a crude solution, but should be working:

desired_list = original_list[:1]
for x in original_list[1:]:
    if desired_list[-1].endswith('\\'):
        desired_list[-1]  = x
    else:
        desired_list.append(x)
print(desired_list)

If you work with huge lists, it may be worth to think of some optimization.

  •  Tags:  
  • Related