📌  相关文章
📜  Python – 通过分隔符连接子字符串

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

Python – 通过分隔符连接子字符串

有时,在使用Python列表时,我们可能会遇到需要在列表中执行字符串连接直到分隔符的问题。这可以应用于我们需要分块数据的领域。让我们讨论可以执行此任务的某些方式。

方法#1:使用循环
这是可以执行此任务的蛮力方式。在此,我们执行加入循环条件语句的任务,并在分隔符出现时将字符串重新初始化为空。

# Python3 code to demonstrate working of 
# Substring concatenation by Separator
# Using loop
  
# initializing list
test_list = ['gfg', 'is', '*', 'best', '*', 'for', 'geeks']
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = '*'
  
# Substring concatenation by Separator
# Using loop
res = []
temp = ''
for sub in test_list:
    if sub != '*':
        temp += sub
    else:
        res.append(temp)
        temp = ''
if temp:
    res.append(temp)
  
# printing result 
print("The list after String concatenation : " + str(res)) 
输出 :
The original list is : ['gfg', 'is', '*', 'best', '*', 'for', 'geeks']
The list after String concatenation : ['gfgis', 'best', 'forgeeks']

方法 #2:使用join() + split() + 列表推导
上述功能的组合可用于执行此任务。在此,我们使用 join() 执行连接任务。列表构造是使用列表推导完成的。

# Python3 code to demonstrate working of 
# Substring concatenation by Separator
# Using join() + split() + list comprehension
  
# initializing list
test_list = ['gfg', 'is', '*', 'best', '*', 'for', 'geeks']
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = '*'
  
# Substring concatenation by Separator
# Using join() + split() + list comprehension
res = [ele for ele in ''.join(test_list).split(K) if ele]
  
# printing result 
print("The list after String concatenation : " + str(res)) 
输出 :
The original list is : ['gfg', 'is', '*', 'best', '*', 'for', 'geeks']
The list after String concatenation : ['gfgis', 'best', 'forgeeks']