Replace words using a dictionary

EasyDictionary Programs · 28 of 94

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

Advertisement
Input
"learning python at sqa-tools", {"at": "is", "sqa-tools": "fun"}
Output
learning python is fun

Approach

  1. Map each word through d.get(word, word).

Solution

Python
text = "learning python at sqa-tools"repl = {"at": "is", "sqa-tools": "fun"}print(" ".join(repl.get(w, w) for w in text.split()))
Output
learning python is fun

Line by line

Line 3

get(w, w) returns the replacement, or the word itself when there is none.

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs