Methods and Functions

Python String maketrans()

The string maketrans() method is a static method. It is used to create a one on one mapping of a character of string to its translation, that is, to specify the list of characters that need to be replaced or deleted from the whole string. A Unicode representation of each character is created by this maketrans() function for transition. In this article, we will be learning about maketrans python method in detail along with some examples.

When used in the translate() method, the translation mapping is used for replacing a character or its mapped character.Let’s say we have a string named string, below is the syntax for implementing maketrans() method on this string:

string.maketrans(x[ ,y[ ,z]]) where y and z are optional parameters.

String maketrans() Parameters

There are three parameters of string maketrans() function:

x: If only one argument is supplied to the maketrans() function, it has to be necessarily a dictionary. This dictionary contains a Unicode number, for example, 97 for ‘a’, to its translation or it contains a one-to-one mapping of a single character of a string to its translation.

y:  If two arguments are supplied to the maketrans() function, they have to be necessarily strings of equal lengths where every character in the first string is a replacement to its corresponding index character present in the second string.

z: In this case, when three arguments are passed, each character is mapped to None.

The return value from String maketrans()

The string maketrans() method returns a transition table with a one-to-one mapping that specifies the conversions that can be used by the translate() method.

Example 1: Translation table using a dictionary with maketrans()

Below is the sample code showing the implementation of maketrans() method with one argument:

Program

                    

# a sample dictionary showing mapping from ‘a’, ‘b’, ‘c’

dictionary = {"a": "555", "b": "666", "c": "777"}

string = "abc"

print(string.maketrans(dictionary))

# a sample dictionary showing mapping from unicode numbers

dict = {109: "111", 110: "222", 111: "333"}

string = "mno"

print(string.maketrans(dictionary))

Output

{97: '555', 98: '666', 99: '777'}

{109: '111', 110: '222', 111: '333'}

Explanation

Firstly, the dictionary named dictionary is defined which contains a one to one mapping of a, b and c to 555 666 and 777 respectively. With the maketrans() function we are replacing the characters of the string as mapped in the dictionary. From the output, we can see that 97(‘a’) is mapped to ‘555’, 98(‘b’) to ‘666’ and 99(‘c’) to ‘777’. Similarly we can verify for the second output as well.

NOTE: An exception is thrown if two or more times the same character is mapped in the dictionary.

Example 2: Translation table using two strings with maketrans()

Below is the sample code showing the implementation of maketrans() method with two arguments:

Program:

                    

first_string = “mno”

second_string = “pqr”

string = “mno”

print(string.maketrans(first_string, second_string))

first_string = “mno”

second_string = “apoyo”

string = “mno”

print(string.maketrans(first_string, second_string))

Output

{109: 112, 110: 113, 111: 114}

=====

Traceback (most recent call last):

File “program.pys3”, line 9, in <module>

print(string.maketrans(first_string, second_string))

ValueError: the first two maketrans arguments must have equal length

Runtime error: exit code is 1

Explanation

In the above code, we can see that when the strings are of equal lengths the transition was created, 109(‘m’) is mapped to 112(‘p’), 110(‘n’) to 113(‘q’) and 111(‘o’) to 114(‘r’). It gave us one to one mapping to each character’s Unicode ordinal in the first string to the Unicode ordinal of the character present in the second string at the same index.

When we try to create a translation table for two strings of unequal length it returns ValueError as shown above.

Example 3: Translational table with removable string with maketrans()

Below is the sample code showing the implementation of maketrans() method with three arguments:

Program

                    

firstString = “mno”

secondString = “pqr”

thirdString = “mnx”

string = “mno”

print(string.maketrans(firstString, secondString, thirdString))

Output

{109: None, 110: None, 111: 114, 120: None}

Explanation

In the above sample example, we can see that first the mapping between characters of the first and second string is created, which is then reset to None for the characters in the first and third string. Mapping for non-existent characters is also created, for example, 120(‘x’) is mapped to None.

Frequently Asked Questions 

Q.1. What does Maketrans do in Python?

Answer: The string maketrans() method is a static method. It is used to create a one on one mapping of a character of the string to its translation, that is, to specify the list of characters that need to be replaced or deleted from the whole string.

A Unicode representation of each character is created by this maketrans() function for transition.

Q.2. How do you translate in Python?

Answer: A Unicode representation of each character is created by the maketrans() function for transition. These mappings are then used by the translate() method to translate in python.

Example: Below is the python program to show the working of the translate() method using mappings created by maketrans() function.

Program

                    

# First String

first_string = “wef”

# Second String

second_string = “eks”

# Third String

third_string = “we”

# Printing the Original String

string = “weeks”

print(“Original string is:”, string)

translation_mapping = string.maketrans(first_string, second_string, third_string)

# Printing the Translated String

print(“Translated string is:”, string.translate(translation_mapping))

Output

The original string is: weeks

The translated string is: ks

Q.3. How do you translate a string in Python?

Answer: To translate a string, the string translate() method is used that returns a modified string in which each character of the string is mapped to the corresponding character as specified in the mapping table. A dictionary containing all the mappings is passed to the translate() method. If some character is not specified in the dictionary in that case it will not be replaced.

Example: Below is the code to demonstrate translations without maketrans() by specifying the mapping using ASCII values.

                    

mappings = { 112 : 119, 121 : 102, 117 : None }

target_string = “peeksyourpeeks”

print (“The string before translating is : “, end =””)

print (target_string)

print (“The string after translating is : “, end =””)

print (target_string.translate(mappings))

Output

The string before translating is : peeksyourpeeks

The string after translating is : weeksforweeks

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

Your email address will not be published. Required fields are marked *

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.