The string method maketrans() in Python returns a mapping table for translation purpose which is usable for translate() method in Python string. In simpler terms, the maketrans() method refers to a static method which creates one to one mapping of a character in the intabstring to its translation/replacement at the same position in the outtab string. It is responsible for creating a Unicode representation of every character for translation.
Note − Both intab and outtab are required to have the similar length.
Following is the syntax for maketrans() method:
- intab − This refers to the string that has actual characters.
- outtab − This is the string that possesses corresponding mapping characters.
This method in Python string returns a translate table which is to be used translate() function.
The example below shows the usage of maketrans() method in Python String. Under this, every vowel within a string gets replaced by its vowel position −
from string import maketrans # Required to call maketrans function.
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!"
When we run above program, it produces following result:
th3s 3s str3ng 2x1mpl2....w4w!!!
Here at Intellinuts, we have created a complete Python tutorial for Beginners to get started in Python.