Skip to content

Python String maketrans() Method

How to use Python's maketrans() method to create character translation tables for string replacements with translate(), including dictionary, two-string, and three-string parameter examples.

The String maketrans() method is a static method that creates a one-to-one mapping of characters to their translations or replacements.

It is primarily used in together with the translate() method to replace specified characters in a string.

Syntax

my_string.maketrans(x, y, z)

maketrans() Parameters

Python String maketrans() method parameters:

Parameter Condition Description
x Required Dictionary (if only one parameter is passed) or String (if two or three parameters are passed)
y Optional String
z Optional String

maketrans() Return Value

Python String maketrans() method returns a translation table with a 1-to-1 mapping of a Unicode ordinal to its translation/replacement.

Examples

Example 1: Translation Table using a Dictionary with maketrans()

The maketrans() method creates a mapping of the character's Unicode ordinal to its corresponding translation.

In the following example,

  • 97 ('a') is mapped to '123'
  • 98 ('b') is mapped to '456'
  • 99 ('c') is mapped to '789'
my_dict = {"a": "123", "b": "456", "c": "789"}
my_str = "abc"
print(my_str.maketrans(my_dict)) # Output: {97: '123', 98: '456', 99: '789'}

output

{97: '123', 98: '456', 99: '789'}

Example 2: Translation Table using two Strings with maketrans()

When the maketrans() method is used with two parameters, it creates a 1-to-1 mapping to each character's Unicode ordinal in first parameter to the same indexed character on second parameter.

In the following example,

  • 97 ('a') is mapped to 100 ('d')
  • 98 ('b') is mapped to 101 ('e')
  • 99 ('c') is mapped to 102 ('f')
firstString = "abc"
secondString = "def"
string = "abc"
print(string.maketrans(firstString, secondString)) # Output: {97: 100, 98: 101, 99: 102}

output

{97: 100, 98: 101, 99: 102}

Example 3: Translational Table with Removable String with maketrans()

When the maketrans() method is used with three parameters, the third parameter resets the mapping of each character in it to None and also creates a new mapping for non-existent characters.

In the following example,

  • thirdString resets the mapping of 97 ('a') to None
  • thirdString resets the mapping of 98 ('b') to None
  • thirdString creates a new mapping for 100 ('d') mapped to None.
firstString = "abc"
secondString = "def"
thirdString = "abd"
string = "abc"
print(string.maketrans(firstString, secondString, thirdString))

output

{97: None, 98: None, 99: 102, 100: None}
Navigation