Python Practice › String Programs › Program 51

Replace several words at once

EasyString Programs · 51 of 106

Write a Python program to replace several words using a dictionary of replacements.

Advertisement
Input
"I'm learning python at Sqatools"; python → SQA, sqatools → TOOLS
Output
I'm learning SQA at TOOLS

Approach

  1. Use a regex that matches any of the words, ignoring case, and look up each replacement.

Solution

Python
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.

More string programs

← All 106 String Programs

Leave a Comment