Tutorial Study Image

Python maketrans()

The maketrans() function in python helps to return a mapping table. The mapping table is used for the translation using the translate() method. The translate() method in python returns a string where each character is mapped to its corresponding character in the mapping table.


string.maketrans(x[, y[, z]]) #where x,y,z are strings
 

maketrans() Parameters:

The maketrans() function takes three parameters. The maketrans() method can create a one-to-one mapping of a character to its translation. This method is a static method.

Parameter Description Required / Optional
x If only one parameter is specified, this has to be a dictionary. If two or more parameters are specified, this parameter has to be a string specifying the characters you want to replace. Required
y A string with the same length as parameter x.Each character in the first parameter will be replaced with the corresponding character in this string. Optional
z A string describing which characters to remove from the original string. Optional

maketrans() Return Value

The return value is a dictionary containing mappings of Unicode characters to its replacement.

Input Return Value
string/dictionary translation table with a 1-to-1 mapping

Examples of maketrans() method in Python

Example 1: How to create Translation table using a dictionary with maketrans()?


dictionary = {"a": "11", "b": "22", "c": "33"}
string1 = "abc"
print(string.maketrans(dict))

 dicti "11", 98: "22", 99: "33"}
string2 = "abc"
print(string2.maketrans(dict))
 

Output:


{97: '11', 98: '22', 99: '33'}
{97: '11', 98: '22', 99: '33'}

Example 2: How to creat Translation table using two strings with maketrans()?



# first string
String1 = "abc"
String2 = "def"
String = "abc"
print(String.maketrans(String1, String2))

# example dictionary
String1 = "abc"
String2 = "defghi"
String = "abc"
print(String.maketrans(String1, String2))
 

Output:


{97: 100, 98: 101, 99: 102}
ValueError: the first two maketrans arguments must have equal length

Example 3: How to creat Translational table with removable string with maketrans()?



String1 = "abc"
String2 = "def"
String3 = "abd"
String = "abc"
print(String.maketrans(String1, String2, String3))
 

Output:


{97: None, 98: None, 99: 102, 100: None}