Saturday, November 16, 2024
Google search engine
HomeLanguagesPython – Replace Substrings from String List

Python – Replace Substrings from String List

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 = ['Lazyroar', '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 : ['Lazyroar', '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 = ['Lazyroar', '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 : ['Lazyroar', '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 = ['Lazyroar', '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 : ['Lazyroar', '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 = ['Lazyroar', '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 : ['Lazyroar', '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 = ['Lazyroar', '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 : ['Lazyroar', '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.

RELATED ARTICLES

Most Popular

Recent Comments