Skip to main content

Python String maketrans() Function

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() function parameters:

ParameterConditionDescription
xRequiredDictionary (if only one parameter is passed) or String (if two or three parameters are passed)
yOptionalString
zOptionalString

maketrans() Return Value​

Python String maketrans() function 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}
note

The two parameters must have the SAME length, otherwise a ValueError exception is raised.

firstString = "abc"
secondString = "defghi"
string = "abc"
print(string.maketrans(firstString, secondString)) # Raises ValueError

output

Traceback (most recent call last):
File "main.py", line 4, in <module>
print(string.maketrans(firstString, secondString))
ValueError: the first two maketrans arguments must have equal length

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}