首页 > 解决方案 > Python将字符串部分连接到带有分隔符的列表中

问题描述

我有一个字符串列表,['what', 'is', 'apple', '&', 'orange'] 仅当 '&' 位于两个字符串之间时才想进行连接。通缉: ['what', 'is', 'apple&orange']

到目前为止我能想到的看起来很愚蠢有没有 Pythonic 的方法来做到这一点?

标签: pythonstringlist

解决方案


l = ['what', 'is', 'apple', '&', 'orange', 'apple', '&', 'banana']

new_list = ' '.join(l).replace(' & ', '&').split()

# print(new_list)
['what', 'is', 'apple&orange', 'apple&banana']

推荐阅读