Python String translate() Method


Contents

Description

The translate() method in Python String of Python programming returns a copy of the string where all the characters have been translated making use of a table which is constructed with the maketrans() function of the Python string module, optionally deleting every character found into the string deletechars.

Syntax

Here is the syntax for translate() method:

str.translate(table[, deletechars]);

Parameters

  • table − You can make use of the maketrans() helper function within the string module in order to create a translation table.
  • deletechars − The list of the characters that are to be removed from the source string.

Return Value

This method in Python string returns a translated copy of the string.

Example

The following example shows the usage of translate() method. Under this every vowel in a string is replaced by its vowel position −

#!/usr/bin/python

from string import maketrans   # Required to call maketrans function.

intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)

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

Below is the example to delete 'x' and 'm' characters from the string:

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

When the above above program is run, it produces the following result:

#!/usr/bin/python

from string import maketrans   # Required to call maketrans function.

intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)

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

This will produce following result:

th3s 3s str3ng 21pl2....w4w!!!

Here at Intellinuts, we have created a complete Python tutorial for Beginners to get started in Python.



Navigation
Tutorial
Tutorial
Tutorial