Python3 translate() Method
Description
The translate()
method translates characters of the string according to the table given by the parameter table
(which includes 256 characters). Characters to be filtered out are placed in the deletechars
parameter.
Syntax
Syntax for the translate()
method:
str.translate(table)
bytes.translate(table[, delete])
bytearray.translate(table[, delete])
Parameters
table
-- The translation table, which is created by themaketrans()
method.deletechars
-- A list of characters to be filtered out from the string.
Return Value
Returns the translated string. If the delete
parameter is provided, characters in the original bytes that belong to delete
are removed, and the remaining characters are mapped according to the table provided.
Example
The following example demonstrates the use of the translate()
function:
Example (Python 3.0+)
#!/usr/bin/python3
intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab) # Create translation table
str = "this is string example....wow!!!"
print (str.translate(trantab))
Output of the above example:
th3s 3s str3ng 2x1mpl2....w4w!!!
The following example demonstrates how to filter out the character 'o':
Example (Python 3.0+)
#!/usr/bin/python
# Create translation table
bytes_tabtrans = bytes.maketrans(b'abcdefghijklmnopqrstuvwxyz', b'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
# Convert to uppercase and remove letter 'o'
print(b'tutorialpro'.translate(bytes_tabtrans, b'o'))
Output of the above example:
b'RUNB'