The maketrans( ) Function is used to create a mapping table that can be used by the translate( ) Function for replacing the values.
x = "Hello World" y = x.maketrans('e','U') z = x.translate(y) print(z)
In the above code, we have declared a String 'Hello World' and assigned it to a variable 'x'.
Then we have used the 'maketrans( )' function to create a table, where 'e' is mapped with 'U'.
And in the next line when the 'translate( )' Function takes the reference of the above mapping table 'y' created by 'maketrans( )',
And replace 'e' with 'U'.
And we get the below output.
Now, what if you want to crete a table with 3 replaceable character. Let us see in the below example.
x = "Hello World" y = x.maketrans('edW','UxP') z = x.translate(y) print(z)
In the above code, we have declared a String 'Hello World' and assigned it to a variable 'x'.
Then we have used the 'maketrans( )' function to create a table, where 'e' is mapped with 'U','d' is mapped with 'x' and 'W' is mapped with 'P'.
And in the next line when the 'translate( )' Function takes the reference of the above mapping table 'y' created by 'maketrans( )',
And replace 'e' with 'U', 'd' with 'x' and 'W' with 'P'.
And we get the below output.
Next, let us say along with the table of replaced values. We also want a table that specifies the values to be removed.
Let us see with the next example.
x = "Hello World" y = x.maketrans('edW','UxP', 'lo') z = x.translate(y) print(z)
In the above code, we have declared a String 'Hello World' and assigned it to a variable 'x'.
Then we have used the 'maketrans( )' function to create a table, where 'e' is mapped with 'U', 'd' is mapped with 'x' and 'W' is mapped with 'P'.
And also specified a third parameter that says the character that has to be removed. And we have specified 'l' and 'o' has to be removed.
And in the next line when the 'translate( )' Function takes the reference of the above mapping table 'y' created by 'maketrans( )',
And replace 'e' with 'U', 'd' with 'x' and 'W' with 'P'. And at the same time, search for 'l' and 'o' and remove it from the String.
And we get the below output.