logo

Python String Maketrans() Method


Show

Description

The string method maketrans() in Python returns a mapping table for translation purposes which is usable for the translate() method in Python string. In simpler terms, the maketrans() method refers to a static method that creates a one-to-one mapping of a character in the into a string to its translation/replacement at the same position in the outta string. It is responsible for creating a Unicode representation of every character for translation.

Note - Both in tab and outta are required to have a similar length.

Syntax

Following is the syntax for maketrans() method:

str.maketrans(intab, outtab)

Parameters

  • intab - This refers to the string that has actual characters.
  • outtab - This is the string that possesses corresponding mapping characters.

Return Value

This method in Python string returns a translate table which is to be used translate() function.

Example

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 -

#!/usr/bin/python

from string import maketrans   # Required to call maketrans function.

intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)

str = "this is string example....wow!!!"
print str.translate(trantab)

When we run the above program, it produces the following result:

th3s 3s str3ng 2x1mpl2....w4w!!!

Here at Intellinuts, we have created a complete Python tutorial for Beginners to get started in Python.