Python

How to Use maketrans in Python 3

How to Use maketrans in Python 3
The maketrans() function is a built-in translate method in Python used to create character-mapping conversion tables. One character is translated into another character via this method. This function can be applied to string and dictionary data to map characters. Unicode representation of the character is used in the translation table. The translate() function is used to convert the data of the translation table into the string data. This tutorial will explain how the maketrans() method can be used in Python for character mapping.

Syntax

string.maketrans(arg1 [, arg2 [, arg3]])

The maketrans() function applies to the content of the string value. This function is able to take three arguments. The first argument is mandatory and the other two arguments are optional. When only one argument is used in this method, then the argument will be a dictionary.  When two arguments are used in this method, then both arguments will be strings of the same length. When three arguments are used in this method, then the third argument will be a string that will remove characters from the string data. The uses of the maketrans() function in string and dictionary data are shown in the examples that follow.

Example 1: Using maketrans() to Translate Key of the Dictionary

The following script shows the use of the maketrans() function for dictionary data. Before, it was mentioned that the maketrans() function takes only one argument for the dictionary variable. A custom function, named make_translation(), is used here to create the translation table based on the provided string value via the maketrans() function. Two for loops and two counters are used here to print the correct character mapped by each ASCII code.

#!/usr/bin/env python3
 
# Define the function to translate the dictionary to translation table
def make_translation(dictVar, strVar):
# Create the translation table
trans_table = strVar.maketrans(dictVar)
print("The original dictionary is: \n", dictVar)
print("The tranlated table of dictionary is: \n",trans_table)
print("\n")
# Initialize the first counter for dictionary
counter1 = 1
for key1 in dictVar:
# Initialize the second counter  for translation table
counter2 = 1
for key2 in trans_table:
if counter1 == counter2:
print("%s is translated to %d" %(key1, key2))
break
# Increment second counter
counter2 = counter2 + 1
# Increment first counter
counter1 = counter1 + 1
 
# Define  a dictionary where key is a string
dictData = "A": 90, "B": 59, "C": 81, "D":75
# Define character list to translate
string = "ABCD"
# Call the translation function
make_translation(dictData,string)

Output:

The following output will appear after running the script. The translation table contains the ASCII code of the key value of the dictionary.

Example 2: Using maketrans() to Translate the Characters of the String

The following example shows the use of maketrans() with string data. Two string values will be taken as search text and replace text, and these text values will be used as arguments for the maketrans() function. You should keep in mind that the length of both the input and the output text must be the same to create the translation table. Otherwise, an error will be generated. The translate() function is used here to convert the translation table data into string values.

#!/usr/bin/env python3
 
# Enter the character list that you want to translate
search = input("Enter the searching characters list \n")
# Enter the character list that you want to replace
replace = input("Enter the replacing characters list \n")
 
# Check the length of searching and replacing character list
if len(search) == len(replace):
 
# Define the string data
original_text = "+8801822594876"
# Create the tranlation table using maketrans()
modified_text = original_text.maketrans(search, replace)
 
# Print the original text
print("The original text is: ", original_text)
# Print the output after applying maketrans()
print("The mapping table output is: ", modified_text)
# Print the output after applying translate()
print("The replaced text is: " , original_text.translate(modified_text))
else:
print("The length of search text and replace text are not equal")

Output

After running the script, 856 is taken as search characters and 487 is taken as replace characters in the following output. In this case, 8 is replaced by 4, 5 is replaced by 8, and 6 is replaced by 7 in the string, '+8801822594878.' The modified output is '+4401422894477.'

Example 3: Using maketrans() to Translate and Delete Characters in the String

The following example shows the uses of three arguments with the maketrans() method. Here, the string is the main string, where the characters of str1 will be searched. If any character matches the chosen character, then that character will be replaced by the corresponding character of str2. If any character of str3 matches with any character of the string variable, then that character will be removed from the string variable. The maketrans() method is called with two arguments for one time and the maketrans() method is called with three arguments for another time.

#!/usr/bin/env python3
 
# Define the main string
string = "Linux"
# Define the character list to search
str1 = "iu"
# Define the character list to replace
str2 = "Ui"
# Define the character list to delete
str3 = "L"
 
# Print the main text
print("The original text: ",string)
 
# Create the translation table
dict1 = string.maketrans(str1, str2)
print("\nThe translation table: \n" ,dict1)
print("The modified string: " ,string.translate(dict1))
 
# Create the translation table after deleting characters
dict2 = string.maketrans(str1, str2, str3)
print("\nThe translation table after deleting the characters: \n", dict2)
# print the modified string after translate
print("\nThe modified string after delete: ", string.translate(dict2))

Output

The following output appears after running the script. Here, 'i' and 'u' characters of 'Linux' are replaced by 'U' and 'i' characters when calling maketrans() with two arguments, and the output is 'LUnix.' When the maketrans() method is called with three arguments, then the character 'L' is deleted by the third argument and the output is 'Unix.'

Conclusion

This tutorial shows how easily you can replace the content of dictionary or string data via the maketrans() method. Particular characters within a string can also be deleted through this method. I hope that the examples shown in this tutorial will help Python users to understand some of the uses of the maketrans() method and will show how to apply this method properly in their own script.

Mouse left-click button not working on Windows 10
If you are using a dedicated mouse with your laptop, or desktop computer but the mouse left-click button is not working on Windows 10/8/7 for some rea...
Cursor jumps or moves randomly while typing in Windows 10
If you find that your mouse cursor jumps or moves on its own, automatically, randomly while typing in Windows laptop or computer, then some of these s...
How to reverse Mouse and Touchpads scrolling direction in Windows 10
Mouse and Touchpads not only make computing easy but more efficient and less time-consuming. We cannot imagine a life without these devices, but still...