Python String translate() Method – Replace Characters Using Mapping

Python String translate() Method

The translate() method returns a new string in which characters have been replaced using a translation table. This is a powerful method when you want to replace or remove multiple characters in a single operation.

Syntax

string.translate(table)

Parameters:

  • table – A translation table created using str.maketrans().

Returns:

  • A new string with specified characters replaced (or removed if mapped to None).

How to Create a Translation Table

Use the str.maketrans() function to build the table. You can map one character to another, or multiple at once.

Example:

table = str.maketrans("abc", "123")

This means: replace 'a' → '1', 'b' → '2', 'c' → '3'

Example: Basic Character Replacement

text = "abc cab"
table = str.maketrans("abc", "123")
result = text.translate(table)
print(result)
123 312

Example: Remove Characters

To remove characters, map them to None.

text = "hello world!"
table = str.maketrans("", "", "aeiou")
result = text.translate(table)
print(result)
hll wrld!

Use Case: Replacing or Deleting Multiple Characters

  • Efficient for replacing multiple characters in one go.
  • Great for creating filters, obfuscation, or cleaning up text data.

Common Mistakes

  • Using translate() without creating a table using maketrans().
  • Mismatch in string lengths when using str.maketrans("abc", "12") – lengths must match.

Interview Tip

translate() is highly efficient when cleaning strings, replacing digits, removing punctuation, or transforming inputs based on character rules.

Summary

  • translate() modifies a string using a mapping table.
  • Use str.maketrans() to create that table.
  • Supports both character replacement and deletion.

Practice Problem

Write a program that replaces all vowels in a string with '*' using translate().

text = "I love Python!"
vowels = "aeiouAEIOU"
replace_with = "*" * len(vowels)
table = str.maketrans(vowels, replace_with)
print(text.translate(table))

Expected Output:

* l*v* Pyth*n!