Search code examples
pythonliststring-concatenation

How to join strings between parentheses in a list of strings


poke_list = [... 'Charizard', '(Mega', 'Charizard', 'X)', '78', '130', ...] #1000+ values

Is it possible to merge strings that start with '(' and end with ')' and then reinsert it into the same list or a new list?

My desired output poke_list = [... 'Charizard (Mega Charizard X)', '78', '130', ...]


Solution

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