Python - Substring concatenation by Separator
Last Updated :
01 Jun, 2023
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.
Python3
# 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))
Output : The original list is : ['gfg', 'is', '*', 'best', '*', 'for', 'geeks']
The list after String concatenation : ['gfgis', 'best', 'forgeeks']
Time Complexity: O(n) where n is the total number of values in the list “test_list”.
Auxiliary Space: O(n) where n is the total number of values in the list “test_list”.
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.
Python3
# 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))
Output : The original list is : ['gfg', 'is', '*', 'best', '*', 'for', 'geeks']
The list after String concatenation : ['gfgis', 'best', 'forgeeks']
Time Complexity: O(n*n), where n is the length of the input list. This is because we’re using the using join() + split() + list comprehension which has a time complexity of O(n*n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.
Method #5: Using regular expressions
- Import the re module for regular expressions.
- Initialize an empty list result.
- Join all the elements in test_list using an empty string as separator and store the result in a variable joined_str.
- Use the re.split() method to split the joined string by the separator K. This method returns a list of substrings.
- Use a list comprehension to iterate over the list of substrings and remove any empty strings. Append each non-empty substring to the result list.
- Print the result list.
Python3
import re
# 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 regular expressions
joined_str = ''.join(test_list)
result = [s for s in re.split(re.escape(K), joined_str) if s]
# printing result
print("The list after String concatenation : " + str(result))
OutputThe original list is : ['gfg', 'is', '*', 'best', '*', 'for', 'geeks']
The list after String concatenation : ['gfgis', 'best', 'forgeeks']
Time complexity: O(n)
Auxiliary space: O(n) (for the result list)
Method #6: Using itertools.groupby()
In this method, groupby() groups the consecutive elements based on the separator (K) passed to the lambda function. k is True for the separator, so we check if not k to filter out the separators. list(g) contains the elements between the separators, which we join using ''.join() to form a string. Finally, we append the resulting string to the list res.
Python3
# Python3 code to demonstrate working of
# Substring concatenation by Separator
# Using loop
from functools import reduce
# 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 itertools.groupby()
res = [''.join(list(g)) for k, g in groupby(test_list, lambda x: x == K) if not k]
# printing result
print("The list after String concatenation : " + str(res))
Output:
The original list is : ['gfg', 'is', '*', 'best', '*', 'for', 'geeks']
The list after String concatenation : ['gfgis', 'best', 'forgeeks']
Time complexity: O(n), where n is the length of the input list. This is because we are iterating through the list only once, and each operation performed inside the loop takes constant time.
Auxiliary space: O(n), as we are creating a new list to store the concatenated substrings.
Similar Reads
Python - Triple quote String concatenation
Sometimes, while working with Python Strings, we can have a problem in which we need to perform concatenation of Strings which are constructed by Triple quotes. This happens in cases we have multiline strings. This can have applications in many domains. Let us discuss certain ways in which this task
4 min read
Python - String Matrix Concatenation
Sometimes, while working with Matrix we can have a problem in which we have Strings and we need a universal concatenation of all the String present in it. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + join() We can solve this problem using lis
4 min read
Input a comma separated string - Python
Handling comma-separated input in Python involves taking user input like '1, 2, 3' and converting it into usable data types such as integers or floats. This is especially useful when dealing with multiple values entered in a single line. Let's explore different efficient methods to achieve this:Usin
3 min read
Python - Concatenate string rows in Matrix
The problems concerning matrix are quite common in both competitive programming and Data Science domain. One such problem that we might face is of finding the concatenation of rows of matrix in uneven sized matrix. Letâs discuss certain ways in which this problem can be solved. Method #1 : Using joi
3 min read
Python - Alternate Strings Concatenation
The problem of getting the concatenation of a list is quite generic and we might someday face the issue of getting the concatenation of alternate elements and get the list of 2 elements containing the concatenation of alternate elements. Letâs discuss certain ways in which this can be performed. Met
3 min read
Python - Split String on all punctuations
Given a String, Split the String on all the punctuations. Input : test_str = 'geeksforgeeks! is-best' Output : ['geeksforgeeks', '!', 'is', '-', 'best'] Explanation : Splits on '!' and '-'. Input : test_str = 'geek-sfo, rgeeks! is-best' Output : ['geek', '-', 'sfo', ', ', 'rgeeks', '!', 'is', '-', '
3 min read
Python | Count overlapping substring in a given string
Given a string and a sub-string, the task is to get the count of overlapping substring from the given string. Note that in Python, the count() function returns the number of substrings in a given string, but it does not give correct results when two occurrences of the substring overlap. Consider thi
2 min read
Python - Remove Punctuation from String
In this article, we will explore various methods to Remove Punctuations from a string.Using str.translate() with str.maketrans()str.translate() method combined with is str.maketrans() one of the fastest ways to remove punctuation from a string because it works directly with string translation tables
2 min read
Python | Get matching substrings in string
The testing of a single substring in a string has been discussed many times. But sometimes, we have a list of potential substrings and check which ones occur in a target string as a substring. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehension Using l
6 min read
Python - Concatenate Ranged Values in String list
Given list of strings, perform concatenation of ranged values from the Strings list. Input : test_list = ["abGFGcs", "cdforef", "asalloi"], i, j = 3, 5 Output : FGorll Explanation : All string sliced, FG, or and ll from all three strings and concatenated. Input : test_list = ["aGFGcs", "cforef", "aa
5 min read