Replace Substrings from String List - Python
Last Updated :
13 Feb, 2025
The task of replacing substrings in a list of strings involves iterating through each string and substituting specific words with their corresponding replacements. For example, given a list a = ['GeeksforGeeks', 'And', 'Computer Science'] and replacements b = [['Geeks', 'Gks'], ['And', '&'], ['Computer', 'Comp']], the updated list would be ['GksforGks', '&', 'Comp Science'] .
Using re
This method is the most efficient for replacing multiple substrings in a list using a single-pass regex operation. It compiles all replacement terms into a pattern, allowing for fast, optimized substitutions without multiple iterations.
Python
import re
# list of strings
a = ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']
# list of word replacements
b = [['Geeks', 'Gks'], ['And', '&'], ['Computer', 'Comp']]
pattern = re.compile("|".join(re.escape(key) for key, _ in b))
replacement_map = dict(b) # Convert `b` to dictionary
a = [pattern.sub(lambda x: replacement_map[x.group()], ele) for ele in a]
print(a)
Output['GksforGks', 'is', 'Best', 'For', 'Gks', '&', 'Comp Science']
Explanation: It compiles a regex pattern to match target substrings and uses a dictionary for quick lookups. It applies re.sub() with a lambda function for single-pass replacements, ensuring efficient and accurate modifications.
Using str.replace()
This approach iterates over the replacement dictionary and applies .replace() to each string. While more readable and simple, it loops multiple times and making it less efficient for large datasets.
Python
# list of strings
a = ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']
# list of word replacements
b = [['Geeks', 'Gks'], ['And', '&'], ['Computer', 'Comp']]
replace_map = dict(b) # convert `b` to dictionary
for key, val in replace_map.items():
a = [ele.replace(key, val) for ele in a]
print(a)
Output['GksforGks', 'is', 'Best', 'For', 'Gks', '&', 'Comp Science']
Explanation: for loop iterates over each key-value pair, replacing occurrences in the string list using str.replace(), ensuring all substrings are updated efficiently.
Using nested loops
A straightforward method that manually iterates through each string and replaces the substrings one by one. While easy to implement, it is slower for larger lists due to multiple iterations.
Python
# list of strings
a = ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']
# list of word replacements
b = [['Geeks', 'Gks'], ['And', '&'], ['Computer', 'Comp']]
replace_map = dict(b) # convert `b` to dictionary
for key, val in replace_map.items():
for i in range(len(a)):
if key in a[i]:
a[i] = a[i].replace(key, val)
print(a)
Output['GksforGks', 'is', 'Best', 'For', 'Gks', '&', 'Comp Science']
Explanation: for loop iterates through each string in the list, checking for substring matches and replacing them using str.replace(), ensuring all occurrences are updated systematically.
Similar Reads
Python - Remove substring list from String Our task is to remove multiple substrings from a string in Python using various methods like string replace in a loop, regular expressions, list comprehensions, functools.reduce, and custom loops. For example, given the string "Hello world!" and substrings ["Hello", "ld"], we want to get " wor!" by
3 min read
Replace substring in list of strings - Python We are given a list of strings, and our task is to replace a specific substring within each string with a new substring. This is useful when modifying text data in bulk. For example, given a = ["hello world", "world of code", "worldwide"], replacing "world" with "universe" should result in ["hello u
3 min read
Python - Remove String from String List This particular article is indeed a very useful one for Machine Learning enthusiast as it solves a good problem for them. In Machine Learning we generally encounter this issue of getting a particular string in huge amount of data and handling that sometimes becomes a tedious task. Lets discuss certa
4 min read
Python | Substring removal in String list While working with strings, one of the most used application is removing the part of string with another. Since string in itself is immutable, the knowledge of this utility in itself is quite useful. Here the removing of a substring in list of string is performed. Letâs discuss certain ways in which
5 min read
Python - Remove suffix from string list To remove a suffix from a list of strings, we identify and exclude elements that end with the specified suffix. This involves checking each string in the list and ensuring it doesn't have the unwanted suffix at the end, resulting in a list with only the desired elements.Using list comprehensionUsing
3 min read