📜  Python - 合并连续的空字符串

📅  最后修改于: 2022-05-13 01:55:46.420000             🧑  作者: Mango

Python - 合并连续的空字符串

有时,在使用Python列表时,我们可能会遇到需要对列表字符串执行合并操作的问题。此合并是连续的,可将多个空格转换为一个。让我们讨论可以执行此操作的特定方式。

方法#1:使用循环
这是可以执行此任务的粗暴方式。在此,我们使用循环查找空字符串,并在创建新列表时忽略连续的字符串。

# Python3 code to demonstrate 
# Merge consecutive empty Strings
# using loop
  
# Initializing list
test_list = ['Gfg', '', '', '', 'is', '', '', 'best', '']
  
# printing original list
print("The original list is : " + str(test_list))
  
# Merge consecutive empty Strings
# using loop
count = 0
res = []
for ele in test_list:
    if ele =='':
        count += 1
        if (count % 2)== 0:
            res.append('')
            count = 0
    else:
        res.append(ele)
  
# printing result 
print ("List after removal of consecutive empty strings : " + str(res))
输出 :
The original list is : ['Gfg', '', '', '', 'is', '', '', 'best', '']
List after removal of consecutive empty strings : ['Gfg', '', 'is', '', 'best', '']