Open In App

Python – Replace Substrings from String List

Last Updated : 23 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes while working with data, we can have a problem in which we need to perform replace substrings with the mapped string to form a short form of some terms. This kind of problem can have applications in many domains involving data. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using loop + replace() + enumerate() 
The combination of the above functions can be used to perform this task. In this, we perform the task of iteration using loop and enumerate() and replacement with a shorter form is done using replace().

Python3




# Python3 code to demonstrate
# Replace Substrings from String List
# using loop + replace() + enumerate()
 
# Initializing list1
test_list1 = ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']
test_list2 = [['Geeks', 'Gks'], ['And', '&'], ['Computer', 'Comp']]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Replace Substrings from String List
# using loop + replace() + enumerate()
sub = dict(test_list2)
for key, val in sub.items():
    for idx, ele in enumerate(test_list1):
        if key in ele:
            test_list1[idx] = ele.replace(key, val)
 
# printing result
print ("The list after replacement : " + str(test_list1))


Output : 

The original list 1 is : ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']
The original list 2 is : [['Geeks', 'Gks'], ['And', '&'], ['Computer', 'Comp']]
The list after replacement : ['GksforGks', 'is', 'Best', 'For', 'Gks', '&', 'Comp Science']

 

Time Complexity: O(n*n) where n is the number of elements in the list “test_list”. 
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”. 

Method #2 : Using replace() + list comprehension 
This is another way in which this task can be performed. In this, we perform the task of replacing using the replace(), and the rest of the task is performed using list comprehension. It removes lists that don’t have replacements.

Python3




# Python3 code to demonstrate
# Replace Substrings from String List
# using replace() + list comprehension
 
# Initializing list1
test_list1 = ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']
test_list2 = [['Geeks', 'Gks'], ['And', '&'], ['Computer', 'Comp']]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Replace Substrings from String List
# using replace() + list comprehension
res = [sub.replace(sub2[0], sub2[1]) for sub in test_list1
      for sub2 in test_list2 if sub2[0] in sub]
 
# printing result
print ("The list after replacement : " + str(res))


Output : 

The original list 1 is : ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']
The original list 2 is : [['Geeks', 'Gks'], ['And', '&'], ['Computer', 'Comp']]
The list after replacement : ['GksforGks', 'Gks', '&', 'Comp Science']

 

Using re:

Here is another approach, using the re module in Python to perform regular expression substitutions:

Python3




import re
 
# Initializing list1
test_list1 = ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']
test_list2 = [['Geeks', 'Gks'], ['And', '&'], ['Computer', 'Comp']]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Replace Substrings from String List using re module
for sub in test_list2:
    test_list1 = [re.sub(sub[0], sub[1], ele) for ele in test_list1]
 
# printing result
print("The list after replacement : " + str(test_list1))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original list 1 is : ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']
The original list 2 is : [['Geeks', 'Gks'], ['And', '&'], ['Computer', 'Comp']]
The list after replacement : ['GksforGks', 'is', 'Best', 'For', 'Gks', '&', 'Comp Science']

Time Complexity: O(n * m * k), where n is the length of the string list test_list1, m is the number of substrings to be replaced, and k is the average length of each string in test_list1.

Space Complexity: O(1), since we only need a constant amount of memory regardless of the size of the input.

Explanation: This approach uses the re.sub() function, which performs a regular expression substitution on a string. We loop through the list of substrings to be replaced, and use a list comprehension to apply the substitution to each string in test_list1. This approach is more versatile than the previous two, as it allows us to use regular expressions to perform the substitutions.

Method #4: Using list comprehension + reduce() + replace() method:

  • Importing the reduce() function from the functools module.
  • Create a dictionary sub from test_list2.
  • Use list comprehension to iterate and replace substrings in each element using reduce() and replace() method.
  • Printing the result.

Python3




# Python3 code to demonstrate
# Replace Substrings from String List
# using list comprehension + reduce() + replace() method
 
from functools import reduce
 
# Initializing list1
test_list1 = ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']
test_list2 = [['Geeks', 'Gks'], ['And', '&'], ['Computer', 'Comp']]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Replace Substrings from String List
# using list comprehension + reduce() + replace() method
sub = dict(test_list2)
res = [reduce(lambda i, j: i.replace(*j), sub.items(), ele) for ele in test_list1]
 
# printing result
print ("The list after replacement : " + str(res))


Output

The original list 1 is : ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']
The original list 2 is : [['Geeks', 'Gks'], ['And', '&'], ['Computer', 'Comp']]
The list after replacement : ['GksforGks', 'is', 'Best', 'For', 'Gks', '&', 'Comp Science']

Time Complexity: O(n*m) where n is the length of test_list1 and m is the length of test_list2.

Auxiliary Space: O(N) where N is the length of test_list1.

Method #5:Using a loop, dictionary, and string methods

  1. Initialize the two lists test_list1 and test_list2.
  2. Initialize an empty list res to store the result.
  3. Create a dictionary sub from the elements of test_list2, where the first element of each sublist is the key and the second element is the value.
  4. Loop through each element ele in test_list1.
  5. Loop through each key in the sub dictionary.
  6. Use the replace() method of the string to replace the key with the corresponding value from the sub dictionary.
  7. Append the modified ele to the res list.
  8. Print the res list as the result of the operation.

Python3




# Initializing list1
test_list1 = ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']
test_list2 = [['Geeks', 'Gks'], ['And', '&'], ['Computer', 'Comp']]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Replace Substrings from String List
# using a loop, dictionary, and string methods
sub = {k:v for k, v in test_list2}
res = []
for ele in test_list1:
    for key in sub:
        ele = ele.replace(key, sub[key])
    res.append(ele)
 
# printing result
print ("The list after replacement : " + str(res))
 
#This code is contributed by Vinay Pinjala.


Output

The original list 1 is : ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']
The original list 2 is : [['Geeks', 'Gks'], ['And', '&'], ['Computer', 'Comp']]
The list after replacement : ['GksforGks', 'is', 'Best', 'For', 'Gks', '&', 'Comp Science']

The time complexity of this solution is O(n*m), where n is the length of the first list, m is the average number of keys in the second list, and l is the average length of the keys and values in the second list.

The space complexity of this solution is O(n), as we create a new list to store the modified strings. The dictionary created from the second list also takes up space proportional to the size of the second list.



Similar Reads

replace() in Python to replace a substring
Given a string str that may contain one more occurrences of “AB”. Replace all occurrences of “AB” with “C” in str. Examples: Input : str = "helloABworld" Output : str = "helloCworld" Input : str = "fghABsdfABysu" Output : str = "fghCsdfCysu" This problem has existing solution please refer Replace all occurrences of string AB with C without using ex
1 min read
Python | Pandas Series.str.replace() to replace text in a series
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. Pandas Series.str.replace() method works like Python .replace() method only, but it works on Series too. Before calling .replace() on a Panda
5 min read
Extract List of Substrings in List of Strings in Python
Working with strings is a fundamental aspect of programming, and Python provides a plethora of methods to manipulate and extract substrings efficiently. When dealing with a list of strings, extracting specific substrings can be a common requirement. In this article, we will explore five simple and commonly used methods to extract substrings from a
3 min read
Extract Substrings From A List Into A List In Python
Python is renowned for its simplicity and versatility, making it a popular choice for various programming tasks. When working with lists, one common requirement is to extract substrings from the elements of the list and organize them into a new list. In this article, we will see how we can extract substrings from a list into a list in Python. Extra
2 min read
Create List of Substrings from List of Strings in Python
In Python, when we work with lists of words or phrases, we often need to break them into smaller pieces, called substrings. A substring is a contiguous sequence of characters within a string. Creating a new list of substrings from a list of strings can be a common task in various applications. In this article, we will create a new list of substring
3 min read
Python | Replace elements in second list with index of same element in first list
Given two lists of strings, where first list contains all elements of second list, the task is to replace every element in second list with index of elements in first list. Method #1: Using Iteration C/C++ Code # Python code to replace every element # in second list with index of first element. # List Initialization Input1 = ['cut', 'god', 'pass']
5 min read
Python | Convert List of String List to String List
Sometimes while working in Python, we can have problems of the interconversion of data. This article talks about the conversion of list of List Strings to joined string list. Let's discuss certain ways in which this task can be performed. Method #1 : Using map() + generator expression + join() + isdigit() This task can be performed using a combinat
6 min read
Python | Grouping similar substrings in list
Sometimes we have an application in which we require to group common prefix strings into one such that further processing can be done according to the grouping. This type of grouping is useful in the cases of Machine Learning and Web Development. Let's discuss certain ways in which this can be done. Method #1 : Using lambda + itertools.groupby() +
7 min read
Python - Find all the strings that are substrings to the given list of strings
Given two lists, the task is to write a Python program to extract all the strings which are possible substring to any of strings in another list. Example: Input : test_list1 = ["Geeksforgeeks", "best", "for", "geeks"], test_list2 = ["Geeks", "win", "or", "learn"] Output : ['Geeks', 'or'] Explanation : "Geeks" occurs in "Geeksforgeeks string as subs
5 min read
Python | Remove Redundant Substrings from Strings List
Given list of Strings, task is to remove all the strings, which are substrings of other Strings. Input : test_list = ["Gfg", "Gfg is best", "Geeks", "for", "Gfg is for Geeks"] Output : ['Gfg is best', 'Gfg is for Geeks'] Explanation : "Gfg", "for" and "Geeks" are present as substrings in other strings.Input : test_list = ["Gfg", "Geeks", "for", "Gf
5 min read
Practice Tags :