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
Python | Split strings and digits from string list Sometimes, while working with String list, we can have a problem in which we need to remove the surrounding stray characters or noise from list of digits. This can be in form of Currency prefix, signs of numbers etc. Let's discuss a way in which this task can be performed. Method #1 : Using list com
5 min read
Python | Remove the given substring from end of string Sometimes we need to manipulate our string to remove extra information from the string for better understanding and faster processing. Given a task in which the substring needs to be removed from the end of the string using Python. Â Â Remove the substring from the end of the string using Slicing In
3 min read
Python | Get the substring from given string using list slicing Given a string, write a Python program to get the substring from given string using list slicing. Letâs try to get this using different examples. What is substring? A substring is a portion of a string. Python offers a variety of techniques for producing substrings, as well as for determining the in
4 min read
Remove spaces from a string in Python Removing spaces from a string is a common task in Python that can be solved in multiple ways. For example, if we have a string like " g f g ", we might want the output to be "gfg" by removing all the spaces. Let's look at different methods to do so:Using replace() methodTo remove all spaces from a s
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 th
3 min read