Python Tutorial Python Advanced Python References Python Libraries

Python String - maketrans() Method



The Python maketrans() method returns mapping table that can be used with the translate() method to replace specified characters.

Syntax

string.maketrans(x, y, z)

Parameters

x Required. If only one argument is specified, it must be a dictionary containing 1-to-1 mapping for translation.
y Optional. It must be a string with equal length as argument x. Each character in the first string will be replaced with the corresponding character in the second string.
z Optional. A string describing characters to remove from the original string. Each character in this argument is mapped to None.

Return Value

Returns the mapping table.

Example: One argument

In the example below, translate() method is to return the translated version of the given string. Here, maketrans() uses one argument to prepare mapping table.

#replace 'L' with 'K'
#and 'H' with 'P'
dict = {'L': 'K', 'H': 'P'}

#preparing the mapping table
MyString = "HELLO"
table = MyString.maketrans(dict)

#print the mapping table
print(table)

#translate and print the string
print(MyString.translate(table))

The output of the above code will be:

{76: 'K', 72: 'P'}
PEKKO

Example: two argument - single character

In the example below, translate() method is to return the translated version of the given string. Here, maketrans() method is used to prepare the mapping table.

str1 = 'L'
str2 = 'K'

MyString = "HELLO"

#preparing the mapping table
#'L' will be replaced by 'K'
table = MyString.maketrans(str1, str2)

#print the mapping table
print(table)

#translate and print the string
print(MyString.translate(table))

The output of the above code will be:

{76: 75}
HEKKO

Example: two argument - multiple characters

In this example, maketrans() method is used to prepare the mapping table to replace multiple characters at once.

str1 = 'HL'
str2 = 'PK'

MyString = "HELLO"

#preparing the mapping table
#'H' will be replaced by 'P'
#'L' will be replaced by 'K'
table = MyString.maketrans(str1, str2)

#print the mapping table
print(table)

#translate and print the string
print(MyString.translate(table))

The output of the above code will be:

{72: 80, 76: 75}
PEKKO

Example: three argument - multiple characters

In this example, third argument of maketrans() method is also used which removes the specified characters.

str1 = 'HL'
str2 = 'PK'
str3 = 'HO'
MyString = "HELLO"

#preparing the mapping table
#first removes 'H' and 'O'
#'H' will be replaced by 'P'
#'L' will be replaced by 'K'
table = MyString.maketrans(str1, str2, str3)

#print the mapping table
print(table)

#translate and print the string
print(MyString.translate(table))

The output of the above code will be:

{72: None, 76: 75, 79: None}
EKK

❮ Python String Methods