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
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 |
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 |
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'}
# 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
String1 = "abc"
String2 = "def"
String3 = "abd"
String = "abc"
print(String.maketrans(String1, String2, String3))
Output:
{97: None, 98: None, 99: 102, 100: None}