Skip to content
Related Articles
Open in App
Not now

Related Articles

Python – Replace Substrings from String List

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 18 Mar, 2023
Improve Article
Save Article

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


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!