首页 > 解决方案 > 如何在字符串列表中的括号之间连接字符串

问题描述

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

是否可以合并以开头'('和结尾的字符串,')'然后将其重新插入到同一个列表或新列表中?

我想要的输出poke_list = [... 'Charizard (Mega Charizard X)', '78', '130', ...]

标签: pythonliststring-concatenation

解决方案


您可以迭代列表元素,检查每个元素是否以 开头(或结尾)。找到括号之间的元素后,可以通过 string.join方法将它们连接起来,如下所示:

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)

flag设置为当1元素在括号内时,0否则,您可以管理所有情况。


推荐阅读