Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




maketrans( ) FUNCTION


maketrans( ) Function


The maketrans( ) Function is used to create a mapping table that can be used by the translate( ) Function for replacing the values.


Example :


x = "Hello World"
y = x.maketrans('e','U')
z = x.translate(y)
print(z)    


Output :



  HUllo World

In the above code, we have declared a String 'Hello World' and assigned it to a variable 'x'.


x = "Hello World"

java_Collections

Then we have used the 'maketrans( )' function to create a table, where 'e' is mapped with 'U'.


y = x.maketrans('e','U')

java_Collections

And in the next line when the 'translate( )' Function takes the reference of the above mapping table 'y' created by 'maketrans( )',


z = x.translate(y)

And replace 'e' with 'U'.


java_Collections

And we get the below output.


HUllo World

Now, what if you want to crete a table with 3 replaceable character. Let us see in the below example.


Example :


x = "Hello World"
y = x.maketrans('edW','UxP')
z = x.translate(y)
print(z) 


Output :



  HUllo Porlx

In the above code, we have declared a String 'Hello World' and assigned it to a variable 'x'.


x = "Hello World"

java_Collections

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'.


y = x.maketrans('edW','UxP')

java_Collections

And in the next line when the 'translate( )' Function takes the reference of the above mapping table 'y' created by 'maketrans( )',


z = x.translate(y)

And replace 'e' with 'U', 'd' with 'x' and 'W' with 'P'.


java_Collections

And we get the below output.


HUllo Porlx

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.


Example :


x = "Hello World"
y = x.maketrans('edW','UxP', 'lo')
z = x.translate(y)
print(z)


Output :



  HU Prx

In the above code, we have declared a String 'Hello World' and assigned it to a variable 'x'.


x = "Hello World"

java_Collections

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.


y = x.maketrans('edW','UxP', 'lo')

java_Collections

And in the next line when the 'translate( )' Function takes the reference of the above mapping table 'y' created by 'maketrans( )',


z = x.translate(y)

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.


java_Collections

And we get the below output.


HU Prx