Python translate() method :
translate() method, as its name suggests, used to translate a string. Or, this is used to replace a set of characters with a different set of characters in a string. Both of the character set is mapped using a table.
For creating the mapping table, one function maketrans() is used. The syntax of this function is as below :
It will map each character of the firstString to secondString. i.e. if firstString is ‘abcde’ and secondString is ‘12345’, ‘a’ is mapped with ‘1’, ‘b’ is mapped with ‘2’ etc. Note that both strings should have equal length. maketrans() returns one string containing this mapping info.
Now, let’s come back to translate() method. This method takes one parameter :
A string that is returned by the maketrans method.
Let me show you with examples to make it more clear (The source code for the below examples are available here) :
Example to use translate() :
In this example, we will simply replace a few characters of a string with different characters :
As you can see that characters a,b,c,d,e are replaced with 1,2,3,4,5 respectively as we have used them in maketrans() method.
If you will try to pass two strings with different length, it will throw one exception like below :
This tutorial has explained to you how to use python translate and maketrans methods. Always pass two strings with equal lengths to avoid the exception. Note that this tutorial is for python 3. On Python 2, translate behaves a little bit differently.
You might also like :