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 :
Example to use translate() :
In this example, we will simply replace a few characters of a string with different characters :
given_str = "The quick brown fox jumps over the lazy dog" table = str.maketrans("abcde","12345") print("Given string : ",given_str) print("String after replacing the characters : ",given_str.translate(table))
It will print the below output :
Given string : The quick brown fox jumps over the lazy dog String after replacing the characters : Th5 qui3k 2rown fox jumps ov5r th5 l1zy 4og
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 :
given_str = "The quick brown fox jumps over the lazy dog" table = str.maketrans("abcde","") print("Given string : ",given_str) print("String after replacing the characters : ",given_str.translate(table))
Traceback (most recent call last): File "example.py", line 4, in table = str.maketrans("abcde","") ValueError: the first two maketrans arguments must have equal length
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 :
- Python Anonymous Lambda Function
- Calendar module in python
- Regular Expression in python
- Python Package
- Python File operations
- Using pip in python