Python translate() method
Description
The Python translate() method converts the characters of a string according to a table (containing 256 characters) given by the table parameter; characters to be filtered out are placed in the del parameter.
Syntax
Syntax of the translate() method:
str.translate(table[, deletechars]);
Parameters
- table -- the translation table, which is created by the maketrans method.
- deletechars -- the list of characters in the string to filter out.
Return Value
Returns the translated string.
Example
The following example shows how to use the translate() function:
Example (Python 2.0+)
#!/usr/bin/python
from
string
import
maketrans
Reference the maketrans function.
intab
=
"
aeiou
"
outtab
=
"
12345
"
trantab
=
maketrans
(
intab
,
outtab
)
str
=
"
this is string example....wow!!!
"
;
str
.
translate
(
trantab
)
;
The output of the above example is:
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!!!
"
;
str
.
translate
(
trantab
,
'
xm
'
)
;
The example above produces the following output:
th3s 3s str3ng 21pl2....w4w!!!
Python Strings