Python – Substring concatenation by Separator

Sometimes, while working with Python Lists, we can have problem in which we need to perform the concatenation of strings in a list till the separator. This can have application in domains in which we need chunked data. Lets discuss certain ways in which this task can be performed.

Method #1 : Using loop
This is brute force way in which this task can be performed. In this, we perform the task of joining in loop conditional statements and re initialize string to empty on separator occurrence.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)) 

chevron_right


Output :

The original list is : ['gfg', 'is', '*', 'best', '*', 'for', 'geeks']
The list after String concatenation : ['gfgis', 'best', 'forgeeks']

 

Method #2 : Using join() + split() + list comprehension
The combination of above functions can be used to perform this task. In this, we perform the task of concatenation using join(). The list construction is done using list comprehension.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)) 

chevron_right


Output :

The original list is : ['gfg', 'is', '*', 'best', '*', 'for', 'geeks']
The list after String concatenation : ['gfgis', 'best', 'forgeeks']



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.