Python maketrans() function
Introduction
A static method is the string maketrans() one. It is used to make a one-to-one mapping between a string's character and its translation, i.e., to define the list of characters that must be added to or subtracted from the entire string. This maketrans() method for transition generates a Unicode representation of each character. This post will go into great detail regarding the maketrans Python method and provide several examples.
The translation mapping is utilized in the translate() function to replace a character or its mapped character. Assuming we have a string called string, the following syntax can be used to apply the maketrans() method to it:
When using the function string.maketrans(a[,b[,c]]), b and c are optional parameters.
maketrans() Parameters for Strings
The string maketrans() function takes three parameters:
- a: If the maketrans() function is given only one argument, it must be a dictionary by definition. This dictionary includes a one-to-one mapping of a single character of a string to its translations or a Unicode number, such as 97 for "a," to its translation.
- b: If the maketrans() method receives two arguments, they must necessarily be equal-length strings with every character in the 1st string serving as a replacement for its corresponding index character in the second string.
- c: In this instance, every character is mapped to None when three arguments are given.
The String maketrans function's return value ()
The translate() function can employ the conversions that are specified in the transition table that the string maketrans() function returns, which has a one-to-one mapping.
Example 1: Using a dictionary and maketrans() to create a translation table
The implementation of the maketrans() function with a single argument is shown in the sample code below:
Code:
# a sample dictionary with mapping from characters "x," "y," and "z"
dict_1 = {"x": "444", "y": "555", "z": "666"}
string = "xyz"
print (string.maketrans (dict_1))
# a model dictionary demonstrating mapping from Unicode numbers
dict_2 = {107: "222", 108: "333", 109: "444"}
string = "mno"
print(string.maketrans(dict_2))
Output:
{120: '444', 121: '555', 122: '666'}
{107: '222', 108: '333', 109: '444'}
Explanation
First, the definition of the dictionary with the name dictionary is given, which maps the letters x, y, and z to the numbers 444, 555, and 666, respectively. The maketrans() function replaces the characters in the string according to how they are represented in the dictionary. We can see from the output that 120("x") is mapped to "444," 121("y") is mapped to "555," and 122("z") is mapped to "666." In a similar manner, we can confirm the second result as well.
NOTE: If a character appears twice or more in the dictionary, an exception is raised.
Example 2: Making use of maketrans() and a translation table with two strings
The implementation of the maketrans() function with 2 arguments is shown in the sample code below:
Code:
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 "d:\Programming\Python\tempCodeRunnerFile.py", line 9, in <module>
print (string.maketrans (first__string, second__string))
ValueError: the first two maketrans arguments must have equal length
Explanation
In the code above, we see that a transition was established when the strings were equal in length; 109("m") is translated to 112("p"), 110("n") to 113("q"), and 111("o") to 114("r"). It provided a one-to-one mapping between each character's Unicode ordinal in the 1st string and the character's Unicode ordinal found at the same index in the 2nd string.
It raises ValueError as seen above when we attempt to establish a translating table for 2 strings that are not the same length.
Example 3: Translation table with detachable string and maketrans()
The maketrans() function with three arguments is implemented in the sample code below:
Code:
first_String = "mno"
second_String = "pqr"
third_String = "mnx"
string = "mno"
print (string.maketrans(first_String, second_String, third_String))
Output:
{109: None, 110: None, 111: 114, 120: None}
Explanation
In the aforementioned test example, we can see that after creating the mapping between the 1st and 2nd string's characters, it is later reset to None for the first and third string's characters. It is also possible to make mappings for nonexistent characters; for instance, 120('x') is mapped to None.
Frequently Asked Questions:
1. What do Python's Maketrans do?
The string maketrans() function is a static method, to be precise. It is used to make a one-to-one mapping between a string's character and its translation, i.e., to define the list of characters that must be added to or subtracted from the entire string.
This maketrans() method for transition generates a Unicode representation of every character.
2. How does Python translate?
The maketrans() method for transition generates a Unicode representation for each character. The translate() function in Python uses these mappings to do the translation.
Here is a Python program that demonstrates how the translate() method works with mappings produced by the maketrans() method.
Code:
# 1st String
first__string = "wef"
# 2nd String
second__string = "eks"
# 3rd String
third__string = "we"
# The Original String being printed
str = "weeks"
print ("Rudimentary str is:", str)
translation__mapping = str.maketrans(first__string, second__string, third__string)
# Printing the Translated String
print ("Translated str is:", str.translate(translation__mapping))
Output:
Rudimentary str is: weeks
Translated str is: ks
3. How does a string get translated in Python?
The string translate() function is used to translate a string, and it produces a changed string in which every character has been mapped to its matching character according to the mapping table. The translate() method receives a dictionary storing all the mappings as an argument. When a character is not listed in the dictionary, it will not be changed.
The code for a translation without maketrans() is shown below as an example. It specifies the mapping utilizing ASCII values.
Code:
mapping = { 111 : 118, 120 : 101, 116 : None }
target__string = "javaTpoint"
print ("Before translating, the string is : ", end ="")
print (target__string)
print ("After translating, the string is : ", end ="")
print (target__string.translate (mapping))
Output:
Before translating, the string is :javaTpoint
After translating, the string is :javaTpvin