Python String translate() Method



The Python string translate() method is a sequel for the maketrans() method in the string module. This method uses the translation table generated by the maketrans() method and translates all characters based on the one-to-one mapping in the said table.

The translation table input for this method, when indexed, performs any of these actions given below −

  • It can be used to retrieve a string or a Unicode ordinal.
  • It maps a character to one or more other characters.
  • It can delete a character from the string retrieved.
  • It raises a LookUpError if a character is mapped to itself.

Note − It works similar to the replace function in a text file.

Syntax

Following is the syntax for Python String translate() method −

str.translate(table);

Parameters

  • table − You can use the maketrans() helper function in the string module to create a translation table.

Return Value

This method returns a translated copy of the string.

Example

Using this method, every vowel in a string is replaced by its vowel position.

The following example shows the usage of Python String translate() method. Here, we are creating two strings: "aeiou" and "12345". We first generate a translation table on these string inputs using the maketrans() method. Then, we call the translate() method on the translation table generated, to get the final string. −

intab = "aeiou"
outtab = "12345"

str = "this is string example....wow!!!";
trantab = str.maketrans(intab, outtab)
print(str.translate(trantab))

When we run above program, it produces following result −

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

Example

We create a translation table as a dictionary and pass it as an argument to the method to obtain the translated string as the return value.

In the following example, we create a string input, say "this is string example....wow!!!", and a translation table as python dictionary. The translate() method is called on the input string where the translation table is passed as an argument.

trantab = {97: 65, 101: 69, 105: 73, 111: 79, 117: 86}

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

Executing the program above will produce following result −

thIs Is strIng ExAmplE....wOw!!!

Example

Another example to demonstrate the usage of translate() method is given below. We take a string "Here, affect is noun" and a python dictionary as the input. The translate() method takes the dictionary as its argument and is called on the input string we created.

trantab = {97: 101}

str = "Here, affect is noun"
print(str.translate(trantab))

If we compile and run the above program, the output is produced as follows −

Here, effect is noun
python_strings.htm
Advertisements