Python translate() method
Description
The Python translate() method converts the characters of a string according to the table (containing 256 characters) given by the parameter table, and places the characters to be filtered out in the del parameter.
Syntax
translate() method syntax:
str.translate(table[, deletechars]);
Parameters
- table -- translation table, which is converted from the maketrans method.
- deletechars -- the list of characters to be filtered out from the string.
Return Value
Returns the translated string.
Examples
The following example demonstrates how to use the translate() function:
Example (Python 2.0+)
#!/usr/bin/python
from string import maketrans # Import the maketrans function.
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!";
print str.translate(trantab);
The output of the above example is as follows:
th3s 3s str3ng 2x1mpl2....w4w!!!
The above example removes the 'x' and 'm' characters from the string:
Example (Python 2.0+)
#!/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');
The output of the above example is:
th3s 3s str3ng 21pl2....w4w!!!
Other Extensions
Python String