How to join strings between parentheses in a list of strings

You can iterate over list element checking if each element starts with ( or ends with ). Once you have find the elements between brackets, you can join them by the string .join method, like this:

poke_list = ['Charizard', '(Mega', 'Charizard', 'X)', '78', '130']

new_poke_list = []
to_concatenate = []
flag = 0

for item in poke_list:
    if item.startswith('(') and not item.endswith(')'):
        to_concatenate.append(item)
        flag = 1
    elif item.endswith(')') and not item.startswith('('):
        to_concatenate.append(item)
        concatenated = ' '.join(to_concatenate)
        new_poke_list.append(concatenated)
        to_concatenate = []
        flag = 0
    elif item.startswith('(') and item.endswith(')'):
        new_poke_list.append(item)
    else:
        if flag == 0:
            new_poke_list.append(item)
        else:
            to_concatenate.append(item)

print(new_poke_list)

The flag is set to 1 when the element is within brackets, 0 otherwise, so you can manage all cases.


Another way to do it, slightly shorter than other solution

poke_list = ['Bulbasaur', 'Charizard', '(Mega', 'Charizard', 'X)', '78', 'Pikachu', '(Raichu)', '130']
fixed = []
acc = fixed
for x in poke_list:
    if x[0] == '(':
        acc = [fixed.pop()]
    acc.append(x)
    if x[-1] == ')':
        fixed.append(' '.join(acc))
        acc = fixed
if not acc is fixed:
    fixed.append(' '.join(acc))
print(fixed)

Also notice that this solution assumes that the broken list doesn't start with a parenthesis to fix, and also manage the case where an item has both opening and closing parenthesis (case excluded in other solution)

The idea is to either append values to main list (fixed) or to some inner list which will be joined later if we have detected opening parenthesis. If the inner list was never closed when exiting the loop (likely illegal) we append it anyway to the fixed list when exiting the loop.

This way of doing things if very similar to the transformation of a flat expression containing parenthesis to a hierarchy of lists. The code would of course be slightly different and should manage more than one level of inner list.