Python String maketrans() Method With Example

Python String maketrans

Now, we are going to learn about the maketrans method. The maketrans method returns a mapping table, usable for the translate method. If we are specifying only one argument here, it should be a dictionary mapping Unicode ordinals(integers) or characters to the Unicode ordinals, strings, or None. Note that this method is a static method.

If we have two arguments, the arguments should be strings of equal length, and in the resulting dictionary, each character in one string would be mapped with the character at the same position in another string. If we have a third argument, it should be a string, whose characters will be mapped to None in the result.

Let’s have a look at a simple example, which would make us understand the maketrans method.

Python String maketrans() Method

As you can see in the above program, we have a dictionary, and then we are calling the maketrans method on some string, and we are passing the dictionary to the maketrans method. Remember that if we are passing one argument, it must be a dictionary.

As an output, we get a mapping table from the maketrans method. Let’s have a look at the output now.

{65: ‘G’, 66: ‘H’, 67: ‘I’}

As you can see that we have got the mapping table. Remember that here, we are passing only one argument to the maketrans method, and in such a situation, we must pass a dictionary here.

Now, Let’s say that we are passing two arguments. In such a case, we should give two strings of the same length. Let’s have a look at a simple program, which demonstrates the same thing.

As you can see in the above program, we have two strings, with the same lengths, and then we are passing those as arguments to the maketrans method. If you try to give strings of unequal length to the maketrans method, it would cause an error. Let’s have a look at the output of the above program.

{65: 71, 66: 89, 67: 97, 68: 110, 69: 105, 70: 80, 71: 97, 72: 110, 73: 100, 74: 105, 75: 116}

As you can see in the output, we got a mapping table, in which each character from one string would be mapped with the character in the same position in another string.

Also, we can pass a third argument, which also must be a string, and all the characters from that string would be mapped to None. Let’s have a look at the sample program for the same.

As you can see in the above program, we are providing three arguments to the maketrans method, and all the arguments are strings. The characters from the third string would be mapped with None. Let’s have a look at the output now.

{65: None, 66: None, 67: None, 68: 110, 69: 105, 70: 80, 71: 97, 72: 110, 73: 100, 74: 105, 75: 116}

As you can see in the output, the characters from the third string are mapped to None. So, as and when required, we can make use of the maketrans method. Basically, it returns a mapping table, which can be usable by the translate method.