Open In App

Replace Substrings from String List - Python

Last Updated : 13 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Share
2 Likes
Like
Report

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.


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.


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.


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.


Next Article
Practice Tags :

Similar Reads