The maketrans()
function helps return the mapping table for translation usable for the translate function(). This means that this function generates the one-to-one mapping of a character to its replacement or translation. The
string.maketrans(x[, y[, z]])
The parameters y
and z
are optional here.
x
: If there is only one parameter, it has to be the dictionary. This dictionary contains the one-to-one mapping from a character to its translation.y
: If we pass two parameters, they have to be two different strings of equal length. Every character in the first string parameter replaces its parallel index in the second string parameter.z
: If we pass three parameters, then every character of the third one will be mapped to none.This function will return the table with a one-to-one mapping of a Unicode ordinal to its replacement or translation.
Here is an example of generating a translation table by using one parameter.
We are using the example dictionary, namely dt1
, in this code. It involves mapping three characters, x
, y
, and z
, to their respective values, 321, 654, and 987. The maketrans()
method generates the mapping for the characters’ Unicode, ordinal to its related translation. 120 (x
) is mapped to 321, 121 (y
) is mapped to 654, and 122 (z
) is mapped to 987. It can be discovered from the output for both of the dictionaries.
dt1= {"x": "321", "y": "654", "z": "987"}my_string = "xyz"print(my_string.maketrans(dt1))# here is the example dictionarydt1 = {120: "321", 121: "654", 122: "987"}my_string = "xyz"print(my_string.maketrans(dt1))
Here is an example of the maketrans()
method with three variables.
In the above-mentioned code, we use str1
and str2
for mapping. These strings cba
and fed
are of equal length. We can get output for the one-to-one mapping of every Unicode, ordinal of the characters in str1
, to the same index of the characters in str2
. We are also working with two strings of different lengths. It will generate the ValueError
exception.
str1 = "cba"str2 = "fed"str = "cba"print(str.maketrans(str1, str2))# here is the example dictionarystr1 = "cba"str2 = "defihg"str = "cba"print(str.maketrans(str1, str2))
Let’s discuss the example regarding the usage of three variables in the maketrans()
method. In the following code, the mapping between the first two strings is generated. The third parameter resets the mapping regarding every character to none.
str1 = "cba"str2 = "fed"str3 = "dba"str = "cba"print(str.maketrans(str1, str2, str3))