Describe
The translate () method converts the character of a string according to the table given by the parameter table (containing 256 characters), and the character to be filtered out is placed in the deletechars parameter.
Grammar
Translate () method syntax:
Str.translate (table[, Deletechars]); Bytes.translate (table[, delete]) bytearray.translate (table[, delete])
Parameters
- Table-translation tables, translation tables are converted through the Maketrans () method.
- Deletechars--a list of characters to filter in the string.
return value
Returns the translated string, and if the delete parameter is given, the delete character in the original bytes is deleted, and the remaining characters are mapped according to the mappings given in the table.
Instance
The following example shows how the translate () function is used:
#!/usr/bin/python3 intab = "Aeiou" Outtab = "12345" Trantab = Str.maketrans (Intab, Outtab) # make translation table str = "This is string EXAMPLE....WOW!!! " Print (Str.translate (trantab))
The result of the above example output is as follows:
TH3S 3s str3ng 2x1mpl2....w4w!!!
The following example shows how to filter out the characters x and M:
#!/usr/bin/python # making translation Table Bytes_tabtrans = Bytes.maketrans (b ' abcdefghijklmnopqrstuvwxyz ', B ' ABCDEFGHIJKLMNOPQRSTUVWXYZ ') # converts to uppercase and removes the letter oprint (b ' runoob '. Translate (Bytes_tabtrans, b ' o '))
The result of the above example output:
B ' Runb '
Python Translate () method