In the previous article we were talking about replacing substrings by other substrings.
You may also want to read about other string methods that I covered in my previous articles. If so, here they are:
In this article we’ll be talking about string mapping.
Here’s the video version of this article:
We can map some characters in the string to other characters. We’ll make use of two methods, which usually work together: maketrans(intab, outtab) and translate.
The former takes 2 arguments: intab and outtab, which are both strings of the same length, and returns a translation table, which is then used by the translate method.
But let’s take it easy:
The translation table maps each character in the intab string to the character in the outtab string which is at the same index. For example we can have the following translation table:
The translation table tells the translate method that it should map each occurrence of the character ‘a’ to ‘y’, ‘e’ to ‘m’, etc.
Here’s how the two methods work together:
>>> intab = "aeiou"
>>> outtab = "ymx.$"
>>> text = "So, after all the changes are applied, you won't recognize this text."
>>> translation_tab = text.maketrans(intab, outtab)
>>> print(text.translate(translation_tab))
S., yftmr yll thm chyngms yrm ypplxmd, y.$ w.n't rmc.gnxzm thxs tmxt.
We can also use the maketrans method with a third parameter, which includes the characters to be deleted.
Let’s see how it works on the same example:
>>> text = "So, after all the changes are applied, you won't recognize this text."
>>> intab = "aeiou"
>>> outtab = "ymx.$"
Before the translate method translates the characters, we want to delete all a’s and l’s from the string:
>>> deltab = "al"
>>> translation_tab = text.maketrans(intab, outtab, deltab)
In the output we can see that there are fewer characters than before due to the fact that some were deleted:
>>> print(text.translate(translation_tab))
S., ftmr thm chngms rm ppxmd, y.$ w.n't rmc.gnxzm thxs tmxt.