Python String translate
Now, we are going to learn about the translate method. Using this method, we get a copy of the string, where each character is mapped to its corresponding character in the translation table. We can say that the translate method takes a translation table, and according to the mapping table, it replaces (or translates) the characters in the given string. Let’s have a look at a simple example, which demonstrates the same thing.
Python String translate() Method
As you can see in the above program, we have two strings, and then we are creating a mapping table, using the maketrans method, and then calling the translate method on the first string. We pass the table as an argument. The return string from the translate method is returned to the newstring method, and then we are printing the string1 and the newstring.
In the returned string, you can find that the characters are mapped to their corresponding characters from the mapping characters. Let’s have a look at the output now.
ABCDEFGHIJK
GyaniPandit
As you can see in the output, each character from the string is mapped with the corresponding character in the mapping table.
So, as and when required, we can make use of the translate method. With the translate method, we get a copy of the string, where each character of the string is mapped to the corresponding character in the mapping table.