Menu Close

Python String maketrans() Method

Python string maketrans

In this tutorial, you will learn all about the Python string maketrans function along with some examples.
Python string maketrans() method is used to return a mapping table that can be used with string translate function.

In the previous tutorial, we have seen the Python string translate method to replace specific characters with another character.

Python string maketrans() method

Python string maketrans() method returns the mapping table that can be used with the string translate method to translate the string .

Syntax

The syntax of maketrans function in python is:-

string.maketrans(x, y, z)

Parameter

The maketrans function in Python is accepts three parameters.

  • x:- Optional. If only one parameter is specified Then it must be a dictionary.
  • y – Optional. If two arguments are passed, it must be two strings with equal length.
  • z:- Optional. A string describing which characters to remove from the original string.

Return Value

The return value of string maketrans function in Python is mapping table.

Python string maketrans example

Here will use maketrans method with some examples so that you can understand easily.
It creates a Unicode representation of each character for replacement.

Example 1:

In this example, we will map a,b and c to 140, 50, and 60.

dict = {"a": "140", "b": "50", "c": "60"}
string = "abc"
print(string.maketrans(dict))

Output:

{97: '140', 98: '50', 99: '60'}

Example 2:

Use string maketrans method with two parameters.

str = 'Hi Mack'
x = 'Mack'
y  = 'Jain'
table = str.maketrans(x, y)
result = str.translate(table)
print(result)

Output will be:- Hi Jain

Example 3:

Use string maketrans method with three parameters.

str = 'Python programming'
x = 'yth'
y  = 'C++'
z = 'Pon'
table = str.maketrans(x, y, z)
result = str.translate(table)
print(result)

Output will be:- ‘C++ prgrammig

In above example, first mapping between x and y are created. Then the third argument z reset the mapping of each character to None.

Note:- The third parameter in the mapping table describe characters that you want to remove from the string.

Conclusion:

In this article, you have learned the Python string maketrans method is used to return a mapping table that can be used with the string translate method to replace the specified characters.

I hope this article will help. If you like this article, please share it with your friends who want to learn Python programming.

Other string method


For More Information:- Click Here

Python String translate() Method
Python String strip() Method

Related Posts