Python String maketrans() Method (original) (raw)

Last Updated : 08 Jan, 2025

maketrans() method in Python is a powerful tool for creating mapping tables that specify how specific characters in a string should be replaced. This method is often used in conjunction with the translate() method to perform character replacements efficiently.

Let’s understand with help of an example:

Python `

Creating a translation table

t = str.maketrans("abc", "xyz")

Translating a string

res = "abcde".translate(t)

print(res)

`

Explanation:

Syntax of maketrans() Method

str.maketrans(x[, y[, z]])

Parameters

  1. **x: A string, dictionary, or sequence of characters that need to be replaced.
  2. y _(optional)_****:** A string with the same length as x, specifying the replacement characters.
  3. z _(optional)_****:** A string containing characters to be removed.

Return Type

Examples of maketrans() Method

1. Basic character mapping

Character mapping refers to associating one set of characters or symbols with another. Replacing vowels with corresponding uppercase letters.

Python `

Create a translation table

t = str.maketrans("aeiou", "AEIOU")

Translating a string

res = "Learn Python with GFG".translate(t)

print(res)

`

Output

LEArn PythOn wIth GFG

Explanation

2. Removing unwanted characters

Removing unwanted characters can be done by using regular expression or simple string operations in Python.

Python `

Create a translation table with characters to remove

t = str.maketrans("", "", ",.!?")

Translating a string

res = "Learn Python, with GFG!".translate(t)

print(res)

`

Output

Learn Python with GFG

Explanation

3. Using a dictionary for mapping

This is useful if we need to replace specific words represented by their initial letters.

Python `

Create a translation table using a dictionary

t = str.maketrans({"L": "D", "w": "v"})

Translating a string

res = "Learn Python with GFG".translate(t)

print(res)

`

Output

Dearn Python vith GFG

Explanation