/  maketrans() method in Python String Module

maketrans() method in Python String Module


maketrans methodin string module is a static method which creates a translation table that can be used for translate() method

maketrans method creates a mapping of the characters and maps itself for translation or replacement.


Syntax:

str.maketrans(x[, y[, z]])


Parameters:

There are 3 parameters in the maketrans method.

  • If a single argument is passed in a program then must be a dictionary. This dictionary should contain one to one mapping from a single character string to its translation i.e. 97 for ‘a’.

Here, 97 is the Unicode translation of ‘a’.

  • If two arguments are passed then it should be passed in two strings of equal length. Each character in the first string is the correspondent index of the other character in the second string.
  • If three arguments are passed then every character in the third argument is mapped to “NONE”.


Here, we can build a translation table with one argument, two arguments, and three arguments.


Example-1: With one argument


In this example, every (key) character in the given key value pair  translated to Unicode representation

str.maketrans({'a': 'b', 'c': None})


Output:


Example 2: With two arguments


In this example, Unicode representation of each character in the given first string mapped with second string.

str.maketrans('abc', 'xyz')


Output:


Example 3: With three arguments


In this example, Unicode representation of each character in the given first string mapped with second string.

From the third String are mapped to None. It means not to replace anything but remove the characters that show up in the string.

str.maketrans('abc', 'xyz', 'hij')


Output: