Python3 translate() Method
Description
The translate() method converts the characters of a string according to the table given by the table parameter (containing 256 characters); the characters to be filtered out are placed in the deletechars parameter.
Syntax
Syntax of the translate() method:
str.translate(table)
bytes.translate(table[, delete])
bytearray.translate(table[, delete])
Parameters
- table -- the translation table, which is produced by the maketrans() method.
- deletechars -- the list of characters in the string to filter out.
Return Value
Returns the translated string; if the delete parameter is given, the characters belonging to delete in the original bytes are removed, and the remaining characters are mapped according to the mapping given in table.
Example
The following example shows how to use the translate() function:
Example (Python 3.0+)
#!/usr/bin/python3
intab
=
"
aeiou
"
outtab
=
"
12345
"
trantab
=
str
.
maketrans
(
intab
,
outtab
)
Build the translation table
str
=
"
this is string example....wow!!!
"
(
str
.
translate
(
trantab
)
)
The output of the above example is:
th3s 3s str3ng 2x1mpl2....w4w!!!
The following example demonstrates how to filter out the character o:
Example (Python 3.0+)
#!/usr/bin/python
Build the translation table
bytes_tabtrans
=
bytes
.
maketrans
(
b
'
abcdefghijklmnopqrstuvwxyz
'
,
b
'
ABCDEFGHIJKLMNOPQRSTUVWXYZ
'
)
Convert to uppercase and delete the letter o
(
b
'
runoob
'
.
translate
(
bytes_tabtrans
,
b
'
o
'
)
)
The example above produces the following output:
b'RUNB'
Python3 Strings