Python String maketrans()
Method
The maketrans()
method is a built-in function used to create a translation table. This table can then be used with the translate()
method to replace specified characters in a string with new characters.
Syntax
str.maketrans(x, y, z)
Parameters:
x
: A dictionary or a string containing characters to be replacedy
: A string with characters to replacex
(must be the same length)z
: (Optional) A string of characters to be removed
Returns:
- A translation table that can be used with
str.translate()
Example 1: Replace Characters Using maketrans()
table = str.maketrans("aeiou", "12345")
text = "hello world"
translated = text.translate(table)
print(translated)
h2ll4 w4rld
Example 2: Remove Characters Using maketrans()
table = str.maketrans("", "", "aeiou")
text = "hello world"
translated = text.translate(table)
print(translated)
hll wrld
Example 3: Use Dictionary in maketrans()
table = str.maketrans({97: 49, 98: 50}) # a → 1, b → 2
text = "abc"
print(text.translate(table))
12c
Use Case: Why Use maketrans()
?
- Efficient way to substitute multiple characters at once
- Used in text preprocessing, encryption, and formatting
- Combines cleanly with
translate()
for powerful string manipulation
Common Mistakes
- Mismatch Length: If
x
andy
are strings, they must be of equal length. - Wrong Type: Don't forget to call
translate()
on the actual string—not on the translation table.
Interview Tip
In coding rounds, maketrans()
+ translate()
is often used for character substitution problems like encoding, sanitizing input, or removing unwanted characters.
Summary
maketrans()
creates a translation table- Used with
translate()
to modify strings - Supports string mapping and character removal
Practice Problem
Write a program that replaces all vowels in user input with *
using maketrans()
.
text = input("Enter some text: ")
table = str.maketrans("aeiouAEIOU", "**********")
print(text.translate(table))