Python Practice › String Programs › Program 52

Replace several characters at once

EasyString Programs · 52 of 106

Write a Python program to replace a with 1, t with 2 and o with 3 in one step.

Advertisement
Input
"Sqatool python"
Output
Sq1233l py2h3n

Approach

  1. Build a translation table with str.maketrans and apply translate.

Solution

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

Advertisement

Learn the concept

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

More string programs

← All 106 String Programs