Python Practice › String Programs › Program 52
Replace several characters at once
Write a Python program to replace a with 1, t with 2 and o with 3 in one step.
Input
"Sqatool python"
Output
Sq1233l py2h3n
Approach
- Build a translation table with
str.maketransand applytranslate.
Solution
text = "Sqatool python"table = str.maketrans({"a": "1", "t": "2", "o": "3"})print(text.translate(table))Output
Sq1233l py2h3n
Line by line
Line 2
maketrans maps each character to its replacement.
Line 3
translate replaces all of them in a single pass.
Learn the concept
New to this topic? Read the lesson, then come back.