String maketrans() in Python

In this tutorial, we will learn about String maketrans() in Python and we will also learn how to use it with the help of various examples.

About String maketrans() in Python

The maketrans() method is a string method that returns a translational table. Since maketrans() is a static method, therefore, it can be called without creating an object.

Syntax:  string.maketrans(x, y, z)

Parameters:

  • string is the string name.
  • This method must contain at least 1 argument, i.e, y, and are optional.
  • It can contain either one, two or three arguments.

maketrans() with Single Argument in Python

If there is only one argument then the argument should be a dictionary and can’t be a string.

Here the key of the dictionary can be Unicode ordinals(integers)or characters. The value of the keys part can be Unicode ordinals or strings or None.

Let us understand this with the help of an example:

string = "welcome to codespeedy"
dict = {"a": "1", "b": "2", "c": "3", "d": "4"} 
#here you can mention 'a' or 97
table = string.maketrans(dict)
print(table)

Output:

{97: '1', 98: '2', 99: '3', 100: '4'}

Explanation

  • Here we want to replace a, b, c, d by 1, 2,3, 4 respectively.
  • We use the maketrans() method to do so.
  • At last, keys a and b are converted back to ordinals.

maketrans() with Two arguments in Python

Syntaxmaketrans(str1,str2)

The strings str1 and str2 must be of equal length.

If the length of the two strings is not equal then it produces an error as:

 ValueError: the first two maketrans arguments must have equal length

Let us understand this with the help of an example:

string = "welcome to codespeedy"
str1 = "abcde"
str2 = "12345"
table = string.maketrans(str1, str2)
print(table)

Output:

{97: 49, 98: 50, 99: 51, 100: 52, 101: 53}

Explanation:

Here a, b, c, d, e is replaced by 1,2,3,4,5 respectively. But here the values are in the Integer representation of Unicode ordinals,i.e, chr(49) = ‘1’.

maketrans() with Three arguments

In this case, the third argument must be a string whose characters will point to None in the final result.

For example:

string = "(welcome$ to* (&codespeedy)"
str1 = "abcde"
str2 = "12345"
str3 = "($&*)"
table = string.maketrans(str1, str2, str3)
print(table)

Output:

{97: 49, 98: 50, 99: 51, 100: 52, 101: 53, 40: None, 36: None, 38: None, 42: None, 41: None}

 

I hope that you were able to understand the concept of String maketrans() in Python. Feel free to ask any questions in the comments section.

You can also read about: String decode() method in Python

Leave a Reply