Python Practice › String Programs › Program 51
Replace several words at once
Write a Python program to replace several words using a dictionary of replacements.
Input
"I'm learning python at Sqatools"; python → SQA, sqatools → TOOLS
Output
I'm learning SQA at TOOLS
Approach
- Use a regex that matches any of the words, ignoring case, and look up each replacement.
Solution
import re text = "I'm learning python at Sqatools"replacements = {"python": "SQA", "sqatools": "TOOLS"}pattern = r"\b(" + "|".join(replacements) + r")\b"print(re.sub(pattern, lambda m: replacements[m.group(0).lower()], text, flags=re.IGNORECASE))Output
I'm learning SQA at TOOLS
Line by line
Line 5
Builds the pattern \b(python|sqatools)\b.
Line 6
For every match the lambda returns the replacement, looked up in lower case.
Learn the concept
New to this topic? Read the lesson, then come back.