Translate a Python String Using a Given Dictionary



In Python, translating the string using a dictionary is used for text manipulation, encoding. It is typically achieved by using the str.translate() method along with the str.maketrans() to define the character mappings.

The dictionary passed to the maketrans() contains key-value pairs where the keys are characters to replace and values are their corresponding replacements. Let's dive into the article to learn more about translating a string using the dictionary.

Using Python str.translate() Method

The Python str.translate() method is a sequel for the maketrans() method in the string module. This method uses the translation table generated by the maketrans() and translate all characters based on the one-to-one mapping in the said table.

Syntax

Following is the syntax of Python str.translate() method ?

str.translate(table)

Python maketrans() Method

The Python maketrans() method is used to create the mapping table for the character replacements, which is then used with the translate() method to replace the specified character.

Syntax

Following is the syntax of Python maketrns() method ?

str.maketrans(x, y, z)

Let's dive into the example, for getting better understanding on translating a string using a dictionary.

Example 1

In the following example, we are going to perform the basic character replacement.

x = str.maketrans({'a': '1', 'b': '2', 'c': '3'})
demo = "abcab"
Result = demo.translate(x)
print(Result)

Output

Output of the above program is as follows ?

12312

Example 2

Consider the following example, where we are going to remove the characters by mapping them to none.

x = str.maketrans('', '', 'aeiou')
demo = "TutorialsPoint"
Result = demo.translate(x)
print(Result)

Output

Output of the above program is as follows ?

TtrlsPnt

Example 3

In the following example, we are going to perform the case conversion using the dictionary.

demo = str.maketrans({'x': 'X', 'b': 'B', 'z': 'T'})
x = "bxz zxb xbz"
Result = x.translate(demo)
print(Result)

Output

Following is the output of the above program ?

BXT TXB XBT

Example 4

Following is the example, where each letter is mapped to its reverse counterpart in the alphabet and observing the output.

import string
x = string.ascii_lowercase
reverse_alphabet = x[::-1]
y = str.maketrans(x, reverse_alphabet)
demo = "tutorialspoint"
Result = demo.translate(y)
print(Result)

Output

If we run the above program, it will generate the following output ?

gfglirzohklrmg
Updated on: 2025-04-14T11:43:53+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements