translate( ) Function
The translate( ) Function is used to replace values specified in the dictionary or 'maketrans( )' Function.
So, there are two ways by which we can use the 'translate( )' Function :
Let us see the first example using a Dictionary.
x = "Hello World" y = {101 : 85} 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 dictionary, where ASCII '101' equivalent of 'e' is mapped with ASCII '85' equivalent of 'U'.
Or,
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, let us look at the example with 'maketrans( )' Function.
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.