Python Tutorial Python Advanced Python References Python Libraries

Python String - translate() Method



The Python translate() method returns the string which is the translated version of the specified string. The method translates specified characters with the characters described in a dictionary, or in a mapping table.

The mapping table is created by the static method maketrans() or dictionary. The dictionary requires ascii codes instead of characters to prepare the mapping table.

Syntax

string.translate(table)

Parameters

table Required. Specify a dictionary or a mapping table describing the replacing between two characters.

Return Value

Returns the translated version of the specified string.

Example:

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)

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

The output of the above code will be:

HEKKO

Example:

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)

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

The output of the above code will be:

PEKKO

Example:

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)

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

The output of the above code will be:

EKK

Using dictionary as mapping table

In this example, dictionary is used as mapping table. To use dictionary as mapping table requires ascii codes instead of characters.

#replace 'L' with 'K'
#and 'H' with 'P'
dict = {76: 75, 72: 80}

MyString = "HELLO"

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

The output of the above code will be:

PEKKO

❮ Python String Methods

5